home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / c / 12804 < prev    next >
Encoding:
Internet Message Format  |  1992-08-26  |  1.7 KB

  1. Path: sparky!uunet!haven.umd.edu!darwin.sura.net!jvnc.net!yale.edu!think.com!barmar
  2. From: barmar@think.com (Barry Margolin)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: dynam mem alloc
  5. Date: 26 Aug 1992 16:18:38 GMT
  6. Organization: Thinking Machines Corporation, Cambridge MA, USA
  7. Lines: 35
  8. Message-ID: <17gasuINNi8@early-bird.think.com>
  9. References: <1992Aug21.191422.28985@news.acns.nwu.edu> <MJN.92Aug26015009@pseudo.uucp>
  10. NNTP-Posting-Host: telecaster.think.com
  11.  
  12. In article <MJN.92Aug26015009@pseudo.uucp> mjn@pseudo.uucp (Murray Nesbitt) writes:
  13. >ecm@casbah.acns.nwu.edu (Edward Malthouse) writes:
  14. >>int *x;
  15. >>if(n == NULL) /* memory has not been allocated */
  16.  
  17. Where did "n" come from?
  18.  
  19. >>This works fine as long as the pointer variable was declared as global or in
  20. >>main().  If it is declared elsewhere this statement does not work.  For
  21. >>example:
  22.  
  23. >Yes, there is a portable way.  Use the storage-class specifier
  24. >``static''.
  25.  
  26. That's not a good answer, since it has more effects than just solving this
  27. problem.  Besides being initialized to 0 automatically, static variables
  28. also retain their value across calls.  So if he frees the object before
  29. returning from the function, the next time he comes in he'll think that the
  30. memory has already been allocated (or worse, since doing anything with a
  31. pointer to freed storage is a no-no).
  32.  
  33. He should just provide an explicit initializer:
  34.  
  35. int *x = NULL;
  36.  
  37. BTW, the fact that it is automatically initialized in main() is just a
  38. feature of that particular implementation.  There is no required default
  39. initialization of automatic or register variables, so you should always
  40. provide an initializer if you care.
  41.  
  42. -- 
  43. Barry Margolin
  44. System Manager, Thinking Machines Corp.
  45.  
  46. barmar@think.com          {uunet,harvard}!think!barmar
  47.