Tracking memory leaks..

Richard Harter g-rh at cca.CCA.COM
Sat Sep 10 15:04:22 AEST 1988


In article <3950011 at eecs.nwu.edu> naim at eecs.nwu.edu (Naim Abdullah) writes:
>I want to check sections of a big program for memory leaks. My basic
>strategy was to define functions xmalloc() and xfree() that would keep
>track of the amount allocated, and to see if the amount went down to
>zero where it should (I wanted to use "#define malloc xmalloc" in the
>main header file to replace occurrences of malloc() and free()).

>The problem with this scheme is that I don't know how much space free()
>will actually free. Here is some sample code, illustrating what I mean:

	If you merely want to know if the amount of space allocated has
gone to zero a much simpler device is to maintain a counter in xmalloc/xfree.
Increment every time you allocate space, decrement it every time you free it.
The value of the counter at any time is the number of allocates for which
there is no corresponding free.  If this number is 0 there are no leaks.
If you want more (i.e. you want to know where the leaks occur) you need
to tie more information to the block.  A quick and dirty way to do this
is to allocate some extra space at the beginning of the block, two words
for a doubly linked list, and one for an address.  When you allocate a 
block link it into the list and load the address xmalloc was called from
in the address field (it is easy to get this address, albeit in a machine
dependent way).  When you free the block delink it.  The result is that
the list gives you, at any time, a list of all addresses of calls to xmalloc
of blocks that have not been deallocated.

-- 

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