home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!cs.utexas.edu!sdd.hp.com!mips!darwin.sura.net!uvaarpa!murdoch!virginia.edu!gs4t
- From: gs4t@virginia.edu (Gnanasekaran Swaminathan)
- Subject: Re: strdup() Was: Re: Renew?
- Message-ID: <1992Jul31.170704.544@murdoch.acc.Virginia.EDU>
- Sender: usenet@murdoch.acc.Virginia.EDU
- Reply-To: gs4t@virginia.edu (Gnanasekaran Swaminathan)
- Organization: University of Virginia
- References: <1992Jul27.201834.13654@Warren.MENTORG.COM> <1992Jul28.163356.3019@taumet.com> <1992Jul29.155252.7632@cbnewsk.cb.att.com> <1992Jul30.161536.29107@virginia.edu>
- Date: Fri, 31 Jul 1992 17:07:04 GMT
- Lines: 36
-
- hansen@pegasus.att.com (Tony L. Hansen) wrote:
- > > #include <string.h>
- > > char *nstrdup(const char *s)
- > > {
- > > if (!s) s = "";
- > > char *ret = new char[strlen(s) + 1];
- > > if (ret) strcpy(ret, s);
- > > return ret;
- > > }
- >
-
- I wrote:
- > Elegant answer but has a little problem.
- >
- > char* ptr = nstrdup(0); // ptr = ""; not allocated by new
- > delete [] ptr; // error
- >
- > Therefore, I suggest the following change.
- >
- > if (!s) return 0;
-
- Tony Hansen corrected me in a private mail. Thanks.
- I incorrectly copied his nstrdup and that is why
- I got that error.
-
- I copied
- if (!s) return "";
- instead of
- if (!s) s = "";
-
- In the latter case, nstrdup correctly returns newed
- memory and hence, delete [] ptr will work.
-
- Sorry for the confusion.
-
- -Sekar
-