Today, I have started writing a tool for finding memory leaks in my programs. So, I have started with defining my own memory functions like malloc, realloc, free with exactly same signature as of the original memory functions. In these functions, I explicitly load original memory libraries, call the original functions and I keep note of how many times each of them is called. So, if I wanted to find memory leaks in a program test, instead of executing it like $./test, I would execute it like $LD_PRELOAD=$PWD/libmemleaks.so ./test.
By mistake, I was explicitly loading /lib/libmemusage.so instead of libc.so. Initially I got so many compilation errors in my libmemleaks.so program. So, I removed lot of code and compiled it again succesfully. But, when I executed it finally, I got a table with heap/stack size and no.of times malloc/calloc/free are called. The table is shown below.
Surprised!! I was not expecting this multi-colored table. I did not write any code for printing this table. In yahoo/google, I searched and did not get any references to this problem [no documentation, problem with open source??]. Then I have used google code search and searched for “Memory usage summary” and got a link to glibc-2.2.5/malloc/memusage.c. After seeing that file, in _fini function, I understood that, they are writing the memory usage report. _fini is the function in shared library which is called, when the system is unloading the library.
After that, I have download glibc 2.2.5 source code and started looking for the clues. In the same directory as glibc-2.2.5/malloc, I found a shell script memusage.sh file. I have copied that into my linux machine and modified a line and executed it [sh memusage.sh ./test]. Then, I got the same multi colored table. Then I came to know, this memusage.so library is written for getting memory stats. memusage.sh, internally executes like LD_PRELOAD= /lib/libmemusage.so <prog.name>. Even I thought of writing my memory leak checking tool with the same concept and at last I have completed my program. But, my program is not as colorful as memusage.sh program. Using memusage.sh, we can find memory stats of any program [including java programs]. Execute sh memusage.sh –help for command help.
Normally, linux distributions dont distribute memusage.sh. You can see the same shell script here. you can download it from here [I have modified at 2 places. Replaced @SLIBDIR@ , @BINDIR@ with /lib, /bin. To get graphs, you need to have memusagestat executable in /bin]. Finally, I am very happy that I found this utility after researching on this for 3 1/2 days.