free()

Stanley Friesen sarima at tdatirv.UUCP
Thu Dec 20 11:21:33 AEST 1990


In article <25898 at uflorida.cis.ufl.EDU> jdb at 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)



More information about the Comp.std.c mailing list