diff --git a/config/zephyr/Kconfig b/config/zephyr/Kconfig index 499a9b93e6..af97b1a200 100644 --- a/config/zephyr/Kconfig +++ b/config/zephyr/Kconfig @@ -462,6 +462,13 @@ config CHIP_MALLOC_SYS_HEAP_WATERMARKS_SUPPORT Enables support for getting current heap high watermark and resetting watermarks. +config CHIP_MALLOC_SYS_HEAP_DEBUG + bool "Log every allocated or freed memory block" + help + Enables debug logs printed whenever a heap memory block is allocated or + freed. The logs can be used to trace the source of memory leaks in the + application. + endif module = MATTER diff --git a/src/platform/Zephyr/SysHeapMalloc.cpp b/src/platform/Zephyr/SysHeapMalloc.cpp index fbd7ba09fc..3f2a65283d 100644 --- a/src/platform/Zephyr/SysHeapMalloc.cpp +++ b/src/platform/Zephyr/SysHeapMalloc.cpp @@ -84,7 +84,13 @@ void * Malloc(size_t size) { LockGuard lockGuard; - return lockGuard.Locked() ? sys_heap_aligned_alloc(&sHeap, kMallocAlignment, size) : nullptr; + void * const mem = lockGuard.Locked() ? sys_heap_aligned_alloc(&sHeap, kMallocAlignment, size) : nullptr; + +#ifdef CONFIG_CHIP_MALLOC_SYS_HEAP_DEBUG + ChipLogProgress(DeviceLayer, "Malloc(%u) = %p, caller: %p", size, mem, __builtin_return_address(0)); +#endif + + return mem; } void * Calloc(size_t num, size_t size) @@ -110,7 +116,13 @@ void * Realloc(void * mem, size_t size) { LockGuard lockGuard; - return lockGuard.Locked() ? sys_heap_aligned_realloc(&sHeap, mem, kMallocAlignment, size) : nullptr; + void * const new_mem = lockGuard.Locked() ? sys_heap_aligned_realloc(&sHeap, mem, kMallocAlignment, size) : nullptr; + +#ifdef CONFIG_CHIP_MALLOC_SYS_HEAP_DEBUG + ChipLogProgress(DeviceLayer, "Realloc(%p, %u) = %p, caller: %p", mem, size, new_mem, __builtin_return_address(0)); +#endif + + return new_mem; } void Free(void * mem) @@ -119,6 +131,10 @@ void Free(void * mem) VerifyOrReturn(lockGuard.Locked()); sys_heap_free(&sHeap, mem); + +#ifdef CONFIG_CHIP_MALLOC_SYS_HEAP_DEBUG + ChipLogProgress(DeviceLayer, "Free(%p), caller: %p", mem, __builtin_return_address(0)); +#endif } #ifdef CONFIG_SYS_HEAP_RUNTIME_STATS