Skip to main content

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 ArchitectureGetting Started Guide
ARM Cortex-MARM Cortex-M Integration Guide
nRF Connect SDKnRF Connect SDK Integration Guide
ESP32 ESP-IDF (Xtensa and RISC-V)ESP32 ESP-IDF Integration Guide
ESP8266ESP8266 RTOS Integration Guide
Dialog DA1469xDA1469x Integration Guide
NXP MCUXpresso RT1060NXP MCUXpresso SDK for i.MX RT Guide
Zephyr RTOSZephyr 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

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")