How to Detect and Fix Memory Leaks in ESP32 FreeRTOS Home Automation Project?
Hi guys I'm working on an ESP32 home automation project using FreeRTOS and MQTT, but the system crashes after a few hours with the error message "Heap allocation failed". I suspect a memory leak in my
createTask
function:
The crash is characterized by a gradual decrease in available memory, leading to a "Guru Meditation Error: Core 0 panic'ed (Heap Allocation Failed)".
To troubleshoot, I monitored heap usage with heap_caps_get_free_size(MALLOC_CAP_8BIT)
and heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT)
, observed a decrease in free memory, verified task creation and deletion with uxTaskGetNumberOfTasks()
, and reviewed other code sections for leaks but found none.
I need help with detecting and fixing memory leaks in ESP32 with FreeRTOS and also suggestions for improving memory management and stability.Solution:Jump to solution
hello @Daniel kalu The issue is that the buffer you allocate with
malloc(1024)
remains in memory even after the task is deleted with vTaskDelete(NULL)
. Since you’re not freeing the buffer using free(buffer), this memory isn’t returned to the heap, leading to the Heap Allocation Failed
error after several iterations.3 Replies
@Daniel kalu Hey there! It sounds like you’re dealing with a tricky memory leak issue, your suspicion about the memory leak in the
createTask
function is valid. I noticed you’re allocating memory with malloc
but not freeing it before the task deletes itself. This would cause a memory leak because each time the task is created and runs, it allocates 1024
bytes of memory that never get freed.Solution
hello @Daniel kalu The issue is that the buffer you allocate with
malloc(1024)
remains in memory even after the task is deleted with vTaskDelete(NULL)
. Since you’re not freeing the buffer using free(buffer), this memory isn’t returned to the heap, leading to the Heap Allocation Failed
error after several iterations.ya