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