ESP32 "CORRUPT HEAP: Bad head" and "Bad tail"

The heap found its own bookkeeping overwritten. The code that crashes is only the code that noticed; the bug is whatever wrote past a buffer, or into memory after freeing it, some time before.

CORRUPT HEAP: Bad tail at 0x3ffe270a. Expected 0xbaad5678 got 0xbaac5678
assertion "head != NULL" failed: file "…/components/heap/multi_heap_poisoning.c", line 201, function: multi_heap_free
abort() was called at PC 0x400dca43 on core 0

Newer ESP-IDF versions print the assertion as assert failed: multi_heap_free multi_heap_poisoning.c:… (head != NULL); the first line is the same.

What it means

ESP-IDF's heap keeps markers next to each allocation and checks them on free and with heap poisoning on. Bad tail: something wrote past the end of a block. Bad head: something wrote before its start, or into a block that was already freed and reused.

The usual causes

Catch the culprit

Espressif's Heap Memory Debugging guide has the details.

Find the line

The Backtrace: line is a list of PC:SP pairs, innermost call first. To turn the addresses into functions and lines you need the ELF of exactly the build that crashed:

When it happens in the field

On your desk the crash prints to the serial monitor. On a device in someone else's building it prints to a port nobody is reading, the chip restarts, and all you hear is that it "sometimes hangs". Pinscope keeps the panic reason and backtrace across the restart, sends them on the next connection and decodes them with the ELF of the build that crashed, so you get the function and line without anyone at the device. Free for three devices. How crash reporting from the field works.

Related errors: Stack overflow · StoreProhibited · LoadProhibited · rst:0x… reset reasons. All ESP32 errors: the list. Messages and causes from ESP-IDF's panic handler and Espressif's Fatal Errors guide.

More