Heap Allocation Tracking
This guide assumes you have already completed the minimal integration of the Memfault SDK. If you have not, please complete the appropriate Getting Started guide.
This feature of the Memfault SDK provides insight into heap allocations when viewing coredumps, for example:
Usage
- Nordic nRF Connect / Zephyr RTOS
- FreeRTOS
- ESP32
- Bare Metal / Other
Add or update the appropriate options to your system's prj.conf
:
CONFIG_MEMFAULT_HEAP_STATS=y
# Setting a non-zero memory pool size is required for heap stats; otherwise
# k_malloc() will not be supported.
CONFIG_HEAP_MEM_POOL_SIZE=512
For systems using the Memfault FreeRTOS port and a FreeRTOS heap
implementation, enable heap tracking with the following configuration options in memfault_platform_config.h
:
#define MEMFAULT_COREDUMP_COLLECT_HEAP_STATS 1
#define MEMFAULT_FREERTOS_PORT_HEAP_STATS_ENABLE 1
For reference, the Memfault SDK port implements the traceMALLOC
/traceFREE
wrappers
here.
1. Enable the config flag
Set this in memfault_platform_config.h
:
#define MEMFAULT_COREDUMP_COLLECT_HEAP_STATS 1
2. Instrument the malloc
and free
calls
For newlib or other typical libc-provided malloc
and free
, you can add the
following wrapper functions (same would apply to other malloc implementations):
#include "memfault/components.h"
extern void __real_free(void *ptr);
extern void *__real_malloc(size_t size);
void __wrap_free(void *ptr) {
MEMFAULT_HEAP_STATS_FREE(ptr);
__real_free(ptr);
}
void *__wrap_malloc(size_t size) {
void *ptr = __real_malloc(size);
MEMFAULT_HEAP_STATS_MALLOC(ptr, size);
return ptr;
}
The MEMFAULT_HEAP_STATS_*
macros will record the malloc
/free
operations.
To enable the wrappers, add these flags to the linker command flags:
-Wl,--wrap=malloc,--wrap=free
ESP32 heap allocation tracking is coming soon!