[comp.lang.c] Why declare returned pointers static?

mike (02/25/91)

In an article, draper@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?

frank@cavebbs.gen.nz (Frank van der Hulst) (03/01/91)

In article <484@bria> uunet!bria!mike writes:
>In an article, draper@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.
>
But the contents of the pointer (i.e. the address of the malloc'ed memory)
is being returned (presumably via CPU registers) to be stored in ably)
yet another DATA_STRUCTURE * variable. So it doesn't matter if the bar
variable inside foo() is lost. Unless TC++ is attempting some garbage
collection at the end of foo(), and doesn't realise that the memory is
still being used, and pointed to in the CPU registers.
 
-- 

Take a walk on the wild side, and I don't mean the Milford Track.