free()

Richard Harter g-rh at cca.CCA.COM
Tue May 10 23:28:00 AEST 1988


In article <2843 at phoenix.Princeton.EDU> mjschmel at phoenix.Princeton.EDU (Michael J. Schmelzer) writes:
>When you free something you've malloc'ed, how does the compiler
>keep track of how large a block you're freeing up?

	Er, I hope that 'compiler' was a slip.  In case it wasn't, the
compiler has nothing to do with it; compilers take your source code
and generate machine executable code from it.

>Obviously, free() and malloc() are machine dependent. So specifically,
>I'm working in Turbo C on an AT. Is it the compiler's job to keep
>tabs on each block that gets allocated by malloc()? What if you just
>freed a random block that wasn't allocated? (Big trouble, but why?)

	Free and malloc are implementation dependent -- they are 
independent library routines.  The quality of implementations vary.
There are a lot of rather cheesy implementations out there.  Nice
allocators keep track of every block allocated and check whether an
address passed to it via free is actually an allocated block.  In a
lot of implementations the control information for the block is placed
just before the block, and the de facto assumption is made that the
address being returned is legitimate.  In these implementations
returning an unallocated block will point the allocator to a garbage
control block.  The code that links and delinks blocks will do something
funny, most likely creating a spurious block and overwriting some data
in an effectively random location.  What happens after that depends
on the details of the allocator; if the allocator places the spurious
freed block in linked list a real disaster will happen when the
spurious block is used.
-- 

In the fields of Hell where the grass grows high
Are the graves of dreams allowed to die.
	Richard Harter, SMDS  Inc.



More information about the Comp.lang.c mailing list