Analyzing heap memory usage with libc allocator API

QNX Tool SuiteIntegrated Development Environment User's GuideDeveloperSetup

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 mallinfo() function returns a mallinfo structure that contains fields that report the used, overhead, and free heap space for memory allocations.

You can attach the debugger and read these variables, which doesn't require modifying an application's code and recompiling it. However, you may prefer to write code that queries and prints memory allocation statistics, to avoid stopping and restarting the program in the debugger (but this strategy requires recompiling). The following code provides an example of how to print some memory allocation information:
#include <malloc.h>
struct mallinfo info = mallinfo();

...

/* Number of arenas. Useful for recognizing contention. */
printf("n_arena %lu\n", info.hblks);

/* Current total size of the arenas. */
printf("arena %lu\n", info.arena);

/* Maximum size of the arenas. Useful for sizing applications. */
printf("max arena %lu\n", info.usmblks);

/* Current total allocated space. */
printf("total alloc %lu\n", info.uordblks);

/* Current total free space. */
printf("total free %lu\n", info.fordblks);

/* Total direct mmapped memory. */
printf("total mmapped %lu\n", info.hblkhd);

Note:
You could output the heap statistics to a file or standard error instead of standard output; the above code is just for demonstrating how to read and print the data fields filled in by libc.

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 free memory) but may not be used directly. The mallinfo structure is defined in the mallinfo() entry in the C Library Reference, which is based off of the mallinfo() entry in the Linux manual page (https://man7.org/linux/man-pages/man3/mallinfo.3.html). Alternatively, you can find a short, descriptive comment next to each field for this structure in QNX_TARGET/usr/include/malloc.h.

Page updated: