home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / cplus / 11768 < prev    next >
Encoding:
Text File  |  1992-07-29  |  1.2 KB  |  38 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!cs.utexas.edu!torn!watserv1!watmath!undergrad.math.waterloo.edu!cayley.waterloo.edu!amewaldu
  3. From: amewaldu@cayley.waterloo.edu (Andrew Walduck)
  4. Subject: Re: strdup() Was: Re: Renew?
  5. Message-ID: <Bs6HK4.8vG@undergrad.math.waterloo.edu>
  6. Sender: news@undergrad.math.waterloo.edu
  7. Organization: University of Waterloo
  8. References: <1992Jul27.201834.13654@Warren.MENTORG.COM> <1992Jul28.163356.3019@taumet.com> <1992Jul29.155252.7632@cbnewsk.cb.att.com>
  9. Date: Thu, 30 Jul 1992 01:31:16 GMT
  10. Lines: 26
  11.  
  12. In article <1992Jul29.155252.7632@cbnewsk.cb.att.com> hansen@pegasus.att.com (Tony L. Hansen) writes:
  13. >
  14. >By the way, at least one person has posted a poor version of strdup() which
  15. >didn't check the return value of new. Here's my contribution. As you can
  16. >see, it is a very straightforward function:
  17. >
  18. >    #include <string.h>
  19. >    char *nstrdup(const char *s)
  20. >    {
  21. >    if (!s) s = "";
  22. >    char *ret = new char[strlen(s) + 1];
  23. >    if (ret) strcpy(ret, s);
  24. >    return ret;
  25. >    }
  26. >
  27. Just remember that to delete storage allocated by this subroutine, you MUST
  28. call delete[] and not delete...
  29.  
  30. Ie:
  31.   char *ptr = nstrdup("Hello");
  32.   delete []ptr; // not delete ptr;
  33.  
  34. Otherwise, things aren't guaranteed to work!! 
  35.  
  36. Andrew Walduck
  37.  
  38.