How to Figure out Who's Hogging Memory?

akolodner25
Posts: 27
Joined: Tue Nov 22, 2022 5:15 am

How to Figure out Who's Hogging Memory?

Postby akolodner25 » Sun Oct 22, 2023 6:25 pm

The latest release of ESP-IDF has a heap memory debugging hook feature*, that allows you to run a function every time memory allocation is performed and succeeds. However, this feature does not exist in v4.4, which means Arduino can't use it, since that requires ESP-IDF v4.4. My problem is that I have something in my program which is taking up a lot of memory, but not quite enough to crash it, so the crash happens right afterwards, and I don't know how to figure out what's causing the large memory footprint, since by the time the crash occurs, it happens in some other allocation call. Is there some analogous way to do memory allocation hooks in v4.4, that's usable by Arduino?

* https://docs.espressif.com/projects/esp ... debug.html
See "Heap Allocation and Free Function Hooks"

lbernstone
Posts: 828
Joined: Mon Jul 22, 2019 3:20 pm

Re: How to Figure out Who's Hogging Memory?

Postby lbernstone » Sun Oct 22, 2023 7:45 pm

These sorts of debug functionalities are typically not included in arduino, since they consume a fair amount of memory to implement.
Rather than expecting a magic debug tool, just watch your memory as you enter and exit functions. I use the following in a header, and then just call MEMCK; around the points of interest. Don't pass objects between functions, that's what pointers are for.

Code: Select all

const char* fmtMemCk = "Free: %d\tMaxAlloc: %d\t PSFree: %d\n";
#define MEMCK Serial.printf(fmtMemCk,ESP.getFreeHeap(),ESP.getMaxAllocHeap(),ESP.getFreePsram())

akolodner25
Posts: 27
Joined: Tue Nov 22, 2022 5:15 am

Re: How to Figure out Who's Hogging Memory?

Postby akolodner25 » Mon Oct 23, 2023 1:06 am

I did this, and I did eventually find where the memory leak was. However, it was tricky, as my app is multithreaded so it was hard to know whether a memory allocation happened during a section of code in one thread, or somewhere else in another. Obviously you could add logging to every thread, but unfortunately the source code of some of the threads (ex: BLE) is not under my control. Would have been nice if Arduino supported something to help figure out memory leaks. Thank you very much for your response!

Who is online

Users browsing this forum: No registered users and 58 guests