home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!cs.utexas.edu!torn!watserv1!watmath!undergrad.math.waterloo.edu!cayley.waterloo.edu!amewaldu
- From: amewaldu@cayley.waterloo.edu (Andrew Walduck)
- Subject: Re: strdup() Was: Re: Renew?
- Message-ID: <Bs6HK4.8vG@undergrad.math.waterloo.edu>
- Sender: news@undergrad.math.waterloo.edu
- Organization: University of Waterloo
- References: <1992Jul27.201834.13654@Warren.MENTORG.COM> <1992Jul28.163356.3019@taumet.com> <1992Jul29.155252.7632@cbnewsk.cb.att.com>
- Date: Thu, 30 Jul 1992 01:31:16 GMT
- Lines: 26
-
- In article <1992Jul29.155252.7632@cbnewsk.cb.att.com> 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;
- > }
- >
- Just remember that to delete storage allocated by this subroutine, you MUST
- call delete[] and not delete...
-
- Ie:
- char *ptr = nstrdup("Hello");
- delete []ptr; // not delete ptr;
-
- Otherwise, things aren't guaranteed to work!!
-
- Andrew Walduck
-
-