mem_debug


mem_debug is a simple module that can be used to find out the memory leaks.

The way of using it is very simple:
Just put the #include <mem_debug.h> line in all the files related to your inquiry and recompile.

The mem_debug.h redirects all the calls to the malloc, calloc and free routines to its own routines, that apart from calling the above routines also prints out into standard input the name of the file, the line, the value of the internal counter and the affected pointer.


An example:

This is the output of a well written program:
filekeeper_lib.c(223)> Malloc   1 = 68538
filekeeper_lib.c(517)> Malloc   2 = 66c88
filekeeper_thread.c(1712)> Malloc   3 = aef20
filekeeper_thread.c(1751)> Free     2 = aef20
filekeeper_thread.c(1807)> Malloc   3 = aef20
filekeeper_thread.c(1886)> Free     2 = aef20
filekeeper_thread.c(3443)> Free     1 = 66c88
filekeeper_lib.c(363)> Free     0 = 68538
As you can see, all the allocated space is freed;

The simplest way to see there (probably) are not any leaks is to see the final value of the index (0 here). It indicates the difference between the allocs an frees. If it is not 0, there IS a memory leak (or you have not included the mem_debug.h in all your files ;)


Here is an example of a program with a memory leak:
filekeeper_lib.c(223)> Malloc   1 = 68538
filekeeper_lib.c(517)> Malloc   2 = 66c88
filekeeper_thread.c(1712)> Malloc   3 = aef20
filekeeper_thread.c(1807)> Malloc   4 = bef21
filekeeper_thread.c(1965)> Free     3 = aef20
filekeeper_thread.c(3443)> Free     2 = 66c88
filekeeper_lib.c(363)> Free     1 = 68538
As you can see, the pointer allocated in filekeeper_thread.c, line 1807 (address bef21) is never freed and the final counter is 1.


Another type of problem are pointers freed more than once. They can be very dangerous since they can corrupt the heap or simply the user data.

Here is an output of such a program:

filekeeper_lib.c(223)> Malloc   1 = 68538
filekeeper_lib.c(517)> Malloc   2 = 66c88
filekeeper_thread.c(1712)> Malloc   3 = aef20
filekeeper_thread.c(1751)> Free     2 = aef20
filekeeper_thread.c(1807)> Malloc   3 = aef20
filekeeper_thread.c(1886)> Free     2 = aef20    <-
filekeeper_thread.c(1965)> Free     1 = aef20    <-
filekeeper_thread.c(3443)> Free     0 = 66c88
filekeeper_lib.c(363)> Free    -1 = 68538
As you can see the pointer with the address aef20 is freed twice; once it was refered to the pointer allocated in line 1807 and once in line 1712 (that was previously freed in line 1751)!


Top of the page.
Send comments to: Igor Sfiligoi

Created:10.11.1999
Last modified:10.11.1999