home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / std / cplus / 2009 < prev    next >
Encoding:
Text File  |  1993-01-08  |  1.8 KB  |  61 lines

  1. Newsgroups: comp.std.c++
  2. Path: sparky!uunet!dynsim1!mbb
  3. From: mbb@litwin.com (Mark Beyleveld)
  4. Subject: Re: initialized 'global' (extern) char arrays
  5. Message-ID: <1993Jan8.135547.26553@litwin.com>
  6. Organization: Litwin Process Automation
  7. References: <1993Jan7.032458.21941@netcom.com> <9300812.4657@mulga.cs.mu.OZ.AU>
  8. Date: Fri, 8 Jan 1993 13:55:47 GMT
  9. Lines: 50
  10.  
  11. jimlynch@netcom.com (Jim Lynch) writes:
  12.  
  13. >I am given to understand that the storage allocated by
  14. >
  15. >char *x = "abcde" ;
  16. >
  17. >is not writable.
  18.  
  19. As was also pointed out, the problem is more subtle, in that somewhere
  20. further into the program, one cannot distinguish between the above, and
  21. strings that were malloc'ed.
  22.  
  23. There are two solutions, depending on what the author intended:
  24.  
  25. 1) If it is supposed to be read-only, declare it as
  26.  
  27.     const char * const x = "abcde" ; 
  28.  
  29. Note that this asserts that the value of the pointer may change, but what
  30. is pointed to is constant.
  31.  
  32. Also, note that unless the constness is deliberately cast away, one
  33. should not be able to attempt to change the data.
  34.  
  35. 2) If it is not to be read-only, 
  36.  
  37.     char * x = strdup("abdce");
  38.  
  39. This is ugly, in that twice the storage is required, but now it is legal 
  40. to say free(x);
  41.  
  42. There is a similar but more subtle problem:
  43.  
  44. char * x = strdup("abcde");
  45. char * y = new char[6];
  46. (void) strcpy(y, "abcde");
  47.  
  48. Further down the road, I want to dispose of the data (which is legal,
  49. since both are dynamically allocated). Do I use free or delete? If
  50. new and delete have not been overloaded, most heap manager implementations
  51. would not care, but this is relying on compiler implementation.
  52.  
  53. One could declare internal coding standards, but if one uses a third-party
  54. library (for which there may be only object code), what then?
  55.  
  56.  
  57. -- 
  58. ---------------------------------------------------------------------
  59. Mark Beyleveld
  60. Litwin Process Automation
  61.