Heap Allocation Tracking
Prerequisite
This guide assumes you have already completed the minimal integration of the Memfault SDK. If you have not, check out the appropriate guide in the table below.
MCU Architecture | Getting Started Guide |
---|---|
ARM Cortex-M | ARM Cortex-M Integration Guide |
nRF Connect SDK | nRF Connect SDK Integration Guide |
ESP32 ESP-IDF (Xtensa and RISC-V) | ESP32 ESP-IDF Integration Guide |
ESP8266 | ESP8266 RTOS Integration Guide |
Dialog DA1469x | DA1469x Integration Guide |
NXP MCUXpresso RT1060 | NXP MCUXpresso SDK for i.MX RT Guide |
Zephyr RTOS | Zephyr Integration Guide |
This feature of the Memfault SDK provides insight into heap allocations when viewing coredumps, for example:
Usage
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
- Other/Bare Metal
- FreeRTOS
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
For Zephyr based projects, that can be added to the appropriate CMakeLists.txt
file as:
zephyr_ld_options("-Wl,--wrap=malloc,--wrap=free")
For systems using the Memfault FreeRTOS port, and a FreeRTOS heap implementation, to enable heap tracking you will want to set this config:
#define MEMFAULT_FREERTOS_PORT_HEAP_STATS_ENABLE 1
For reference, the Memfault SDK port implements the traceMALLOC
/traceFREE
wrappers
here.