[an error occurred while processing this directive]
Node:malloc crash,
Next:Crash traceback,
Previous:v2 crash,
Up:Running
malloc
or free
.Q: Since I upgraded to DJGPP v2.02, my program started to crash, and
the traceback points to library function free
. This program
worked flawlessly with v2.01, so I guess there's a bug in the new
version of free
, right?
A: Such problems are a tell-tale sign of programs that overwrite
buffers allocated by malloc
or calloc
, or call free
more than once with the same pointer, or pass to free
a pointer
that didn't originate from a call to malloc
or calloc
. If
the program that crashes is a C++ program, you might have several
objects that share the same data, and the object destructor crashes when
it calls free
several time with the same memory chunk.
These crashes happen inside the memory-allocation functions because
these functions maintain some crucial information about the allocated
and free memory blocks right before the beginning and beyond the end of
the allocated buffers. For speed considerations, this information is
not protected by any means like CRC or parity, so if you overwrite this
information, malloc
and free
will become confused and
eventually will blow up.
The version of malloc
in DJGPP library before v2.02 left some
slack space beyond the end of the allocated buffer (this was a
side-effect of the algorithm it used, which was optimized for speed, but
wasted some memory). Thus, a program could overrun the allocated buffer
and still get away uncaught. The new version of malloc
introduced with v2.02 doesn't waste memory, and because of this is much
less tolerant to such bugs.
Bottom line: you should debug your program to find the offending code that overwrites the end of an allocated buffer. One way of doing that is to put a data breakpoint (a.k.a. watchpoint) inside a debugger at the address which gets overwritten; then, when the program overwrites it, the debugger will kick in and you will see whodunit.
Another possibility to debug such problems is to use the YAMD package, written and maintained by Nate Eldredge. YAMD is a malloc debugger which will catch and report many problems related to allocating, freeing, and using allocated memory. YAMD is available from Nate's home page.