It is possible to get memory allocation statistics performed by malloc and related functions within your program.
There are a few alternatives to get allocation stats. First one is mallinfo(void)
which returns a struct mallinfo.
But mallinfo has some drawbacks (see: mallinfo (3))
You can use malloc_info(int, FILE*)
to print detailed information as xml string on a FILE* file pointer or stderr.
If neither want to print standard output nor a regular file, but you want to take back xml strings in a memory area pointed by a char* pointer, you can use open_memstream(char**, size_t*)
function to get a FILE*
pointer which address a dynamically allocated memory area. With this model, you have to manually free up allocated buffers.
Here is an example program and its outputs:
char *buf;
size_t size;
FILE *fp = open_memstream(&buf, &size);
malloc_info(0, fp);
fclose(fp);
/* do whatever you want with buf pointer */
evbuffer_add_printf(out, "# Memory Allocation Stats\n%s\n#> ", buf);
free(buf);
Output:
<malloc version="1">
<heap nr="0">
<sizes>
<size from="65" to="80" total="80" count="1"/>
<size from="65" to="65" total="65" count="1"/>
<size from="97" to="97" total="97" count="1"/>
<size from="465" to="465" total="465" count="1"/>
<size from="32625" to="32625" total="32625" count="1"/>
<size from="302209" to="302209" total="302209" count="1"/>
<size from="1528385" to="1528385" total="1528385" count="1"/>
<unsorted from="2689" to="2689" total="2689" count="1"/>
</sizes>
<total type="fast" count="1" size="80"/>
<total type="rest" count="7" size="1866535"/>
<system type="current" size="6631424"/>
<system type="max" size="6631424"/>
<aspace type="total" size="6631424"/>
<aspace type="mprotect" size="6631424"/>
</heap>
<heap nr="1">
<sizes>
<size from="433" to="433" total="433" count="1"/>
</sizes>
<total type="fast" count="0" size="0"/>
<total type="rest" count="1" size="433"/>
<system type="current" size="135168"/>
<system type="max" size="135168"/>
<aspace type="total" size="135168"/>
<aspace type="mprotect" size="135168"/>
</heap>
<total type="fast" count="1" size="80"/>
<total type="rest" count="8" size="1866968"/>
<system type="current" size="6766592"/>
<system type="max" size="6766592"/>
<aspace type="total" size="6766592"/>
<aspace type="mprotect" size="6766592"/>
</malloc>