🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #2213

Re: free()

#2213
From: Stanley Friesen
Date: Thu, 20 Dec 1990 00:21
37 lines
1953 bytes
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)
Technical Details
Message-ID: <82@tdatirv.UUCP>
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!rutgers!att!news.cs.indiana.edu!samsung!cs.utexas.edu!uunet!tdatirv!sarima
References: <25898@uflorida.cis.ufl.EDU>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!rutgers!att!news.cs.indiana.edu!samsung!cs.utexas.edu!uunet!tdatirv!sarima
From: sarima@tdatirv.UUCP (Stanley Friesen)
Newsgroups: comp.std.c
Subject: Re: free()
Message-ID: <82@tdatirv.UUCP>
Date: 20 Dec 90 00:21:33 GMT
References: <25898@uflorida.cis.ufl.EDU>
Reply-To: sarima@tdatirv.UUCP (Stanley Friesen)
Distribution: usa
Organization: Teradata Corp., Irvine
Lines: 37