Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!ncar!tank!nucsrl!naim From: naim@eecs.nwu.edu (Naim Abdullah) Newsgroups: comp.lang.c Subject: Tracking memory leaks.. Message-ID: <3950011@eecs.nwu.edu> Date: 9 Sep 88 01:59:06 GMT Organization: Northwestern U, Evanston IL, USA Lines: 65 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 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@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,..