Analyzing heap memory usage with libc allocator API
The libc library contains a data structure that you can read to retrieve statistics about the current heap memory usage. These statistics are more detailed than those reported by the System Information and can be read at precise code locations.
The _malloc_stats structure contains fields that report the used, overhead, and free heap space for both big
and small blocks. For instance, the m_allocmem field stores the space in use by the program for big blocks.
Here, space in use
means how much memory was requested and doesn't include memory for storing block metadata.
Likewise, the m_small_allocmem field stores the space in use for small blocks,
which are blocks stored in bands preallocated by libc to improve performance.
- m_allocs, m_reallocs, and m_frees — the allocation, reallocation, and free counts
- m_overhead and m_small_overhead — the overhead used for big and small block headers
- m_heapsize — the full size of the heap, including internal fragmentation
#include <malloc.h>
extern struct malloc_stats _malloc_stats;
...
printf("Used memory: %d\n", (_malloc_stats.m_allocmem + _malloc_stats.m_small_allocmem));
These statistics give you insight into the overhead that the memory allocator is generating and how much memory is being handed out to your application (and thus, shows up in a pidin memory listing as heap memory) but may not be used directly. In this SDP release, the _malloc_stats structure is defined in QNX_TARGET/usr/include/malloc.h. A short, descriptive comment is provided next to each field.
