home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!cis.ohio-state.edu!pacific.mps.ohio-state.edu!linac!att!att!cbnewsk!pegasus!hansen
- From: hansen@pegasus.att.com (Tony L. Hansen)
- Subject: Re: strdup() Was: Re: Renew?
- Organization: AT&T
- Date: Fri, 31 Jul 1992 14:39:32 GMT
- Message-ID: <1992Jul31.143932.13345@cbnewsk.cb.att.com>
- Summary: look again
- Keywords: strdup, null pointers
- References: <1992Jul28.163356.3019@taumet.com> <1992Jul29.155252.7632@cbnewsk.cb.att.com> <1992Jul30.161536.29107@murdoch.acc.Virginia.EDU>
- Sender: hansen@cbnewsk.cb.att.com (tony.l.hansen)
- Lines: 59
-
- < From: gs4t@virginia.edu (Gnanasekaran Swaminathan)
- <
- < hansen@pegasus.att.com (Tony L. Hansen) writes:
- << #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;
- << }
- <
- < 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;
-
- Look again.
-
- It's not the value of "" which is returned, but a new'd copy of "" which is
- returned. If the pointer passed in is a null pointer, then that pointer is
- replaced with a value of "", which is then copied into the new'd space. In
- other words, it's always the value which came from operator new which is
- returned, and never the value of "".
-
- Here's a version of nstrdup() which is heavily commented:
-
- /*
- NAME
- nstrdup - duplicate string into new'd heap space
-
- SYNOPSIS
- char *nstrdup(const char *string)
-
- DESCRIPTION
-
- The nstrdup() function allocates storage space (with a call to
- operator new) for a copy of string, and returns a pointer to the
- storage space containing the copied string. The function returns 0
- if operator new returned 0. If the string pointer is null, an empty
- string is used in its place.
- */
-
- #include <string.h>
- char *nstrdup(const char *s)
- {
- if (!s) s = ""; // if null pointer, use empty string default
- char *ret = new char[strlen(s) + 1]; // allocate space
- if (ret) strcpy(ret, s); // copy string
- return ret; // return value returned by operator new
- }
-
- Tony Hansen
- hansen@pegasus.att.com, tony@attmail.com
- att!pegasus!hansen, attmail!tony
-