[LCP]Segmentation Faults when calling free()

Matthew Palmer mjp16 at ieee.uow.edu.au
Thu Feb 20 14:04:01 UTC 2003


On Wed, 19 Feb 2003, Chuck Martin wrote:

> Could someone tell me what might cause free() to segfault?  I've
> verified that the memory has been previously allocated (using malloc()),
> the correct pointer is being passed to free(), and the memory hasn't
> already been freed with a previous call to free(), so what else could
> it be?

Metadata corruption.

Didn't quite catch that?  <grin>  I'll give you the full story, then.

Malloc and friends know about blocks of memory only because they've stored
some hidden information about those blocks in memory.  In most[1]
implementations, the information about how big an allocated block of memory
is, whether it's free or used, etc, is stored immediately before the block
which is given to you.  So, for instance, you might have been given the
address 12d in response to a malloc() call.  In address 8d-11d, there might
be some metadata which says "this block is 80 bytes long, and is in use".

That's all well and good, until you have an overflow somewhere which writes
into this space.  What used to say "this block is 80 bytes long" might now
say "this block is 10000080 bytes long" (or some other very large number). 
So, when free() goes in to shag with it, it'll probably exceed the
boundaries of allocated (via the underlying paging system, rather than the
malloc() way) pages, and hence cause el Segfault.

Solution?  Compile with electric fence, and run in a debugger.  Efence
causes a segfault on the first instruction which writes outside the n bytes
which you've been specifically allocated (and hence catches overruns,
underruns, and fencepost errors).  Very, very useful for finding bugs like
this.

[1] FVO "most" that include "the couple that I've actually bothered to check
the internals of".  I don't want counts of which do it this way, and which
do it other ways.


-- 
-----------------------------------------------------------------------
#include <disclaimer.h>
Matthew Palmer, Geek In Residence
http://ieee.uow.edu.au/~mjp16





More information about the linuxCprogramming mailing list