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

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!cs.utexas.edu!sdd.hp.com!mips!darwin.sura.net!uvaarpa!murdoch!virginia.edu!gs4t
  3. From: gs4t@virginia.edu (Gnanasekaran Swaminathan)
  4. Subject: Re: strdup() Was: Re: Renew?
  5. Message-ID: <1992Jul31.170704.544@murdoch.acc.Virginia.EDU>
  6. Sender: usenet@murdoch.acc.Virginia.EDU
  7. Reply-To: gs4t@virginia.edu (Gnanasekaran Swaminathan)
  8. Organization: University of Virginia
  9. References: <1992Jul27.201834.13654@Warren.MENTORG.COM> <1992Jul28.163356.3019@taumet.com> <1992Jul29.155252.7632@cbnewsk.cb.att.com> <1992Jul30.161536.29107@virginia.edu>
  10. Date: Fri, 31 Jul 1992 17:07:04 GMT
  11. Lines: 36
  12.  
  13. hansen@pegasus.att.com (Tony L. Hansen) wrote:
  14. > >    #include <string.h>
  15. > >    char *nstrdup(const char *s)
  16. > >    {
  17. > >    if (!s) s = "";
  18. > >    char *ret = new char[strlen(s) + 1];
  19. > >    if (ret) strcpy(ret, s);
  20. > >    return ret;
  21. > >    }
  22.  
  23. I wrote:
  24. > Elegant answer but has a little problem.
  25. > char* ptr = nstrdup(0); // ptr = ""; not allocated by new
  26. > delete [] ptr;        // error
  27. > Therefore, I suggest the following change.
  28. > if (!s) return 0;
  29.  
  30. Tony Hansen corrected me in a private mail. Thanks.
  31. I incorrectly copied his nstrdup and that is why
  32. I got that error.
  33.  
  34. I copied
  35.     if (!s) return "";
  36. instead of
  37.     if (!s) s = "";
  38.  
  39. In the latter case, nstrdup correctly returns newed
  40. memory and hence, delete [] ptr will work.
  41.  
  42. Sorry for the confusion.
  43.  
  44. -Sekar
  45.