[comp.std.c] free

jdb@reef.cis.ufl.edu (Brian K. W. Hook) (12/13/90)

Okay, I know this is going to be a stupid question to a lot of you, but I
am just a tad curious.  According to the C-reference manuals, you pass
free a pointer to a block of memory that you want deallocate.  Eg.

char *a;

a=malloc(80);
if (a) free(a);

Now what happens if, oh, you do THIS:

foo()
{
int x;

x=10;
if (x) free (&x);
}

I know that malloc uses heap space and that the local variables take up the
stack, so what happens?  &x is NOT null so it will try to free it, so what
happens?  Also, in a similar vein, are global variables allocated on the heap
or stack?  All replies would be appreciated.

sarima@tdatirv.UUCP (Stanley Friesen) (12/20/90)

In article <25898@uflorida.cis.ufl.EDU> jdb@reef.cis.ufl.edu (Brian K. W. Hook) writes:
 
>Now what happens if, oh, you do THIS:
>foo()
>{
>int x;
 
>x=10;
>if (x) free (&x);
>}
 
>I know that malloc uses heap space and that the local variables take up the
>stack, so what happens?  &x is NOT null so it will try to free it, so what
>happens?

Shit happens.  Exactly what shit happens depends on the implementation.
Since this is in the realm of undefined behavior a conforming implementation
is allowed to launch a pre-emptive stike against Iraq.

On most existing UNIX implementations of malloc()/free() this will insert
one or more random blocks of memory into malloc's free block list.  Since
at least part of one of these blocks (including the block header) is on
the stack a subsequent subroutine is going to use the same exact memory
for automatic variables and trash the block header.  Voila, the next call
to malloc() will now dump core.  (If it has not already done so because an
invalid block is on the free list.)

> Also, in a similar vein, are global variables allocated on the heap
>or stack?  All replies would be appreciated.

This is not specified in the standard. In almost all implementations they
are found in a third, completely distinct, area of memory, the data segment.
[In general memory is usually divided into about 4 big pieces, the program
text, the static data, the stack, and the heap.]
-- 
---------------
uunet!tdatirv!sarima				(Stanley Friesen)