</>EmbeddedInterview

How do you detect a stack overflow on a microcontroller?

MediumPointers & Memory

Short answer: Combine several techniques: stack painting (fill the stack with a known pattern at boot and check how much was overwritten), a guard region below the stack using the MPU, hardware stack limit registers on Armv8-M (MSPLIM/PSPLIM), the RTOS's overflow checks, and static worst-case stack analysis at build time.

1. Stack painting (high-water mark)

extern uint32_t _sstack, _estack;          /* from the linker script */
#define STACK_FILL 0xDEADBEEFu

void stack_paint(void)                     /* call very early, before the stack is deep */
{
    uint32_t *p = &_sstack;
    uint32_t *sp = (uint32_t *)__get_MSP();
    while (p < sp - 16) *p++ = STACK_FILL; /* leave a margin below the current SP */
}

size_t stack_unused_bytes(void)
{
    const uint32_t *p = &_sstack;
    while (p < &_estack && *p == STACK_FILL) p++;
    return (size_t)((const uint8_t *)p - (const uint8_t *)&_sstack);
}

Report the minimum ever over long tests; keep a safety margin (e.g. 25%).

2. MPU guard region: configure a small no-access region just below each stack. An overflow triggers a MemManage fault immediately, at the instruction that overflowed, instead of corrupting other data. FreeRTOS-MPU and Zephyr (CONFIG_MPU_STACK_GUARD) do this per thread.

3. Stack limit registers (Cortex-M23/M33/M55/M85): set MSPLIM and PSPLIM; any instruction that moves SP below the limit raises a UsageFault (STKOF). No MPU region needed.

4. RTOS checks: FreeRTOS configCHECK_FOR_STACK_OVERFLOW = 1 checks the stack pointer at each context switch; = 2 also checks that the last 16 bytes of the stack still contain the fill pattern; vApplicationStackOverflowHook() is called on detection. uxTaskGetStackHighWaterMark() reports the minimum free stack per task.

5. Static analysis: compile with -fstack-usage (a .su file per source with each function's frame size) and combine with the call graph (-fcallgraph-info, puncover, StackAnalyzer) to compute the worst case. Recursion and function pointers break the analysis, which is one reason they are restricted in safety code.

6. Canaries: -fstack-protector-strong puts a guard value between local buffers and the return address and checks it on return; this detects buffer overruns within a frame (a security feature, not a full overflow detector).

Symptoms of an undetected overflow: random variable corruption, HardFaults with nonsense addresses, crashes that depend on interrupt timing, and bugs that disappear when you add a printf (which changes stack usage).