home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!usc!sdd.hp.com!swrinde!cs.utexas.edu!torn!cunews!nrcnet0!bnrgate!bcrka451!bcrki65!sjm
- From: sjm@bcrki65.bnr.ca (Stuart MacMartin)
- Newsgroups: comp.lang.c++
- Subject: Re: strdup() Was: Re: Renew?
- Message-ID: <1992Jul31.141149.11647@bcrka451.bnr.ca>
- Date: 31 Jul 92 14:11:49 GMT
- References: <9221219.25266@mulga.cs.mu.OZ.AU> <1992Jul27.173054.396@taumet.com> <1992Jul27.201834.13654@Warren.MENTORG.COM> <1992Jul28.163356.3019@taumet.com> <1992Jul29.155252.7632@cbnewsk.cb.att.com>
- Sender: 5E00 Corkstown News Server
- Reply-To: sjm@bcrki65.bnr.ca (Stuart MacMartin)
- Organization: Bell-Northern Research, Ottawa, Canada
- Lines: 41
-
- In article <9221219.25266@mulga.cs.mu.OZ.AU>, fjh@munta.cs.mu.OZ.AU
- (Fergus James HENDERSON) writes:
- > hansen@pegasus.att.com (Tony L. Hansen) writes:
- >
- > >By the way, at least one person has posted a poor version of strdup() which
- > >didn't check the return value of new. Here's my contribution. As you can
- > >see, it is a very straightforward function:
- > >
- > > #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;
- > > }
- >
- > If you ask me, the check for ``if (!s) s = "";'' is a really bad idea.
- > If the program passes you a NULL pointer, then you do NOT want to silently
- > correct it, you want to let the programmer know that an error has occured.
-
- This is a matter of whether or not you consider this to be an error.
- In C, it was annoying that realloc did not treat NULL as a request for
- malloc. It is personal preference whether this should be allowed in realloc
- or handled in a higher-level macro. Similarly, if free(s) did nothing if
- s was NULL, it would have saved a lot of bugs due to people forgetting to do
- if (s) free(s).
-
- This case is slightly different, because there is more than one obvious
- way to handle 0 legally: return 0 or return a pointer to "". Personally,
- I don't consider the gain made by treating 0 input as an error to be worth
- the pain. Anyone who wants to write robust code will use your less efficient
- form. And anyway, the strcpy(ret,s) instead of memcpy(ret,s,len) is a far
- more expensive coding luxury. (Set len = strlen(s) + 1 before the new).
-
- Stuart
-
- : Stuart MacMartin email: sjm@bnr.ca :
- : Bell-Northern Research phone: (613) 763-5625 :
- : PO Box 3511, Stn C, Ottawa, K1Y-4H7, CANADA Standard disclaimers apply. :
-