Why declare returned pointers static?
Frank van der Hulst
frank at cavebbs.gen.nz
Fri Mar 1 19:19:14 AEST 1991
In article <484 at bria> uunet!bria!mike writes:
>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.
>
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.
More information about the Comp.lang.c
mailing list