memory allocation problems

Michael J Zehr tada at athena.mit.edu
Mon Dec 31 12:49:37 AEST 1990


Someone wrote:
> [help -- memory leak!!]

What I do is use allocation/deallocation macros something like:

#define _new(type) (type *)malloc_debug(sizeof(type), __FILE__, __LINE__)

and a similar one for free.  then in malloc_debug and free_debug i have
code that writes the pointer being allocated/freed with the file name
and line number to a log file.  (making sure the pointer is at the same
position in each line.)

because the pointers are at the same position you can do a sort on the
log file and collect all the lines regarding a particular memory
location together... (it should be a stable sort so if the same location
is returned more than once by malloc you can still sort out the file.)

then it should be pretty clear which mallocs have no associated frees.

the set of #defines above are #ifdef-ed to something like DEBUG so you
can compile without the extra overhead once you're sure there aren't any
memory leaks.

(i've used this to find memory leaks in 20,000 line programs in 5
minutes.  *much* easier than poring over code or something like that.)

-michael j zehr
software engineer
consultants for management decisions, inc.



More information about the Comp.lang.c mailing list