Why declare returned pointers static?

uunet!bria!mike uunet!bria!mike
Tue Feb 26 01:49:29 AEST 1991


In an article, draper at galaxy.cps.msu.edu (Patrick J Draper) writes:
|DATA_STRUCTURE *foo ()
|{
| static DATA_STRUCTURE *bar;
|
|   bar = (DATA_STRUCTRE *) malloc (sizeof (DATA_STRUCTRE));
|   return (bar);
|}
|
|and called like this:
|DATA_STRUCTRE *bar;
|
|   bar = foo ();
|
|My question is: Why does this work? Is the malloc'd space static and not
|the pointer? From my tests with Turbo C++, with a static pointer, the
|malloc'd space never gets overwritten accidentally. With a normal
|pointer, the malloc'd space can be corrupted by things like another
|malloc, etc.

Memory that has been allocated ala malloc() is global within the context
of the process allocating it.  The pointer is not.  Remember, when you
declare a pointer, you *are* declaring storage (for the address).  If the
pointer is an automatic variable, the memory that contains the address
is released unless it is declared static.  Your chunk of memory that you
grabbed with malloc() is still there; the pointer to it is not.

-- 
Michael Stefanik, MGI Inc., Los Angeles| Opinions stated are not even my own.
Title of the week: Systems Engineer    | UUCP: ...!uunet!bria!mike
-------------------------------------------------------------------------------
Remember folks: If you can't flame MS-DOS, then what _can_ you flame?



More information about the Comp.lang.c mailing list