home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / lang / cplus / 13370 < prev    next >
Encoding:
Text File  |  1992-09-08  |  2.0 KB  |  72 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!news.mentorg.com!sdl!adk
  3. From: adk@Warren.MENTORG.COM (Ajay Kamdar)
  4. Subject: Re: can I 'delete' without a 'new'?
  5. Message-ID: <1992Sep7.182055.8329@Warren.MENTORG.COM>
  6. Organization: Mentor Graphics Corp. - IC Group
  7. References: <1992Sep4.171020.4762@kentrox.uucp>
  8. Date: Mon, 7 Sep 1992 18:20:55 GMT
  9. Lines: 61
  10.  
  11. In article <1992Sep4.171020.4762@kentrox.uucp> peter@kentrox.uucp (Peter Uchytil) writes:
  12. >I can't seem to find any references which indicate whether I can do this
  13. >or not, so I'm appealing to the net.wisdom.  Here's what I've got:
  14. >
  15. >class foo {
  16. >  char *String;
  17. >public:
  18. >  foo();
  19. >  foo( char * );
  20. >  ~foo();
  21. >  void set( char * );
  22. >};
  23. >
  24. >foo:foo() { };
  25. >
  26. >foo:foo( char *inString ) {
  27. >  String = new char[strlen( inString )];
  28. >  strcpy( String, inString );
  29. >}
  30. >
  31. >void foo:set( char *inString ) {
  32. >  String = new char[strlen( inString )];
  33. >  strcpy( String, inString );
  34. >}
  35. >
  36.     You have a severe bug in the above code. When you new a character array
  37.     to hold a copy of the inString, you want to allocate space for ONE MORE
  38.     than the length of the string (to hold the terminating '\0'). i.e.,
  39.     String = new char[strlen(inString) + 1+;
  40.     strcpy(String, inString);
  41.  
  42.  
  43. >foo:~foo() {
  44. >  delete [] String;
  45. >}
  46. >
  47. >The question is what will happen if I create a foo with the empty constructor
  48. >and never call 'set'?  Since 'new' has never been called, what will 'delete'
  49. >try to delete?  Looks like a real good way to frazzle the system.  Yes?  No?
  50. >
  51.  
  52.     Yes, a real good way to frazzle the system. What you want to do is
  53.     to set String to 0 in the default constructor as follows:
  54.  
  55.     foo::foo() : String(0) {}
  56.  
  57. >
  58. >But then does 'set' first have to do a 'delete' before doing another 'new'?
  59. >I would assume it does.
  60. >
  61.  
  62.      Yes, you need to do a delete before doing a new in set().
  63.  
  64.  
  65. - Ajay
  66.  
  67. -- 
  68. I speak for none but myself.
  69.  
  70. Ajay Kamdar                               Email : ajay_kamdar@mentorg.com
  71. Mentor Graphics, IC Group (Warren, NJ)    Phone : (908) 580-0102
  72.