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-IDFESP32 ESP-IDF Integration Guide
ESP8266ESP8266 RTOS Integration Guide
Dialog DA1469xDA1469x 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