Finding memory leaks with mallinfo()
I’ve been programming computers since 1983 or so, professionally since 1987 or so. Somehow, in all that time, I never knew about mallinfo(). Today, faced with debugging a memory leak, I googled around a bit, and came across mallinfo.
struct mallinfo mallinfo (void)
The structure it returns contains, according to the info page:
-
int arena
This is the total size of memory allocated with sbrk by malloc, in bytes.
-
int ordblks
This is the number of chunks not in use. (The memory allocator internally gets chunks of memory from the operating system, and then carves them up to satisfy individual malloc requests; see Efficiency and Malloc.)
-
int smblks
This field is unused.
-
int hblks
This is the total number of chunks allocated with mmap.
-
int hblkhd
This is the total size of memory allocated with mmap, in bytes.
-
int usmblks
This field is unused.
-
int fsmblks
This field is unused.
-
int uordblks
This is the total size of memory occupied by chunks handed out by malloc.
-
int fordblks
This is the total size of memory occupied by free (not in use) chunks.
-
int keepcost
This is the size of the top-most releasable chunk that normally borders the end of the heap (i.e., the high end of the virtual address space’s data segment).
The interesting fields for finding memory leaks are, I think, “uordblks” and “fordblks”, which are the Used and Free space malloc has grabbed from the OS.
I made a couple of macros:
#define M1 mi1 = mallinfo() #define M2(x) mi1 = mi2; mi2 = mallinfo(); if (mi1.uordblks != mi2.uordblks) \ fprintf(stderr, "%s consumed %d\n", (x), mi2.uordblks - mi1.uordblks)
Then, to use this, around any function call which might contain a memory leak but which should not allocate any memory, first declare mi1 and mi2:
struct mallinfo mi1, mi2
Then, surround the function call with M1 and M2 macros:
M1; some_function_call() M2("some_function_call"); M1; some_other_function_call(); M2("some_other_function_call");
By using those macros in a classical “wolf fence” method, I was rather easily able to find the memory leak in my program today, which was a pleasant surprise.
<p>See also: mtrace
Just so that you know, mallinfo() is deprecated in many operating systems, and you can’t entirely trust the statistics provided by mallinfo.
For example glibc uses arenas and mallinfo shows info for only one of it.