Tracking memory leaks..

Naim Abdullah naim at eecs.nwu.edu
Fri Sep 9 11:59:06 AEST 1988


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:
===============================Cut Here============================
#include <stdio.h>
extern char *malloc();

static unsigned int alloc_size = 0;

char *xmalloc(size)
unsigned int size;
{
    char *p;
    if ((p = malloc(size)) != NULL)
        alloc_size += size;
    return p;
}

xfree(p)
char *p;
{
    unsigned int size_being_freed;
    size_being_freed = *((unsigned int *)(p - OFFSET)); /* probably wrong */
    alloc_size -= size_being_freed;
    free(p);
}

unsigned int bytes_allocated()
{
    return alloc_size;
}

main()
{
    char *p1, *p2;
    p1 = xmalloc(10);
    p2 = xmalloc(99);
    xfree(p1);
    printf("%u bytes still allocated.\n", bytes_allocated());
}
=====================================================================

Now, I don't know what to define OFFSET to be. I would like this to be
portable between VAXen running 4.3bsd and Sun3s running SunOS 3.x, but if
that is not possible, having it work on any one machine would be ok too.

Any suggestions for the value of OFFSET or what the function xfree() should
look like ?

Thank you.

		      Naim Abdullah
		      Dept. of EECS,
		      Northwestern University

		      Internet: naim at eecs.nwu.edu
		      Uucp: {oddjob, chinet, att}!nucsrl!naim

P.S: There was a paper on "mprof" in the latest USENIX. That can be used to
track down memory leaks as well as give you a lot of other information.
Hopefully, it will be in the next BSD but until then,..



More information about the Comp.lang.c mailing list