home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!utcsri!geac!r-node!pseudo!mjn
- From: mjn@pseudo.uucp (Murray Nesbitt)
- Subject: Re: dynam mem alloc
- Organization: Private system in Toronto, ON
- Date: Sun, 30 Aug 1992 10:33:11 GMT
- Message-ID: <MJN.92Aug30023311@pseudo.uucp>
- References: <1992Aug21.191422.28985@news.acns.nwu.edu> <MJN.92Aug26015009@pseudo.uucp> <17gasuINNi8@early-bird.think.com>
- Sender: mjn@pseudo.uucp (Murray Nesbitt)
- Lines: 56
-
-
- barmar@think.com (Barry Margolin) writes:
-
- >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).
-
- You're telling me this like I don't already know what ``static'' does.
-
- The way I understood his article was that he was looking for a way to
- ensure a pointer variable with block scope would 1) be initialized to
- NULL, and 2) retain its value between invocations of the block, so
- that he would be able to malloc() some memory only in the first
- invocation of the block, and on subsequent invocations be able to
- reliably test whether memory had already been allocated to the
- pointer.
-
- >
- >He should just provide an explicit initializer:
- >
- >int *x = NULL;
- >
-
- No, he shouldn't, because each time the block is executed, x will be
- set to NULL. If all he was looking for was a way to initialize a
- pointer to NULL when entering a block of code, do you *really* think
- he wouldn't have thought of this method?
-
- >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.
-
- I think it's more likely that the variable in question just happened
- to have the initial value 0, as opposed to being explicitly
- initialized by the implementation.
-
- --
- Murray
-