Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Fundamentals 13 min read

Five Ways to Detect Stack Overflow in Embedded Systems: From Sentinels to MPU Protection

This article details five stack overflow detection methods for embedded systems: stack painting with sentinel values, compiler-based stack canaries, MPU memory protection, physical memory separation, and post-crash register analysis, with code examples and trade-off analysis for each approach.

A Variable That Changes Itself

A project exhibited a fault where the device's display status jumped randomly after running for several minutes. The root cause was a global variable g_state being overwritten to 0. This variable was only assigned in three places within a state machine, each protected by a default case. After two days of searching, no write path was found.

A data breakpoint revealed the write instruction was inside memcpy, called by parse_frame, which had a 128-byte local array. The incoming frame was 140 bytes — a classic stack overflow. The overflow wrote past the stack bottom, landing exactly on

g_state</sub>.</p><p>Key insight: <strong>stack overflow does not crash immediately</strong>. The CPU happily writes to the out-of-bounds address. By the time symptoms appear, the crash site is far from the actual corruption.</p><h2>Method 1: Fill Sentinels, Watch the Watermark</h2><p>On startup, fill the entire stack region with <code>0xCD

. After running, scan from low address upward; the first byte not equal to 0xCD marks the peak usage (watermark). Remaining 0xCD bytes were never touched.

#define STK_FILL  0xCDCDCDCDu
extern uint32_t _estack;

void stack_paint(uint32_t size) {
    uint32_t *p = (uint32_t *)((uint8_t *)&_estack - size);
    while (p < &_estack) *p++ = STK_FILL;
}

uint32_t stack_peak(uint32_t size) {
    uint32_t *p = (uint32_t *)((uint8_t *)&_estack - size);
    while (p < &_estack && *p == STK_FILL) p++;
    return (uint8_t *)&_estack - (uint8_t *)p;
}

Pros: zero cost, no hardware or compiler support needed. Cons:

Only reflects executed paths. If test case 101 exercises a deeper path (1.8 KB vs observed 1.2 KB), the overflow goes undetected.

Filling too early misses pre-main usage. C++ global constructors and library init run before main; fill must happen in Reset_Handler before jumping to main.

Fill value may be misread. A local variable legitimately equal to 0xCDCDCDCD skews the watermark. Probability is low but non-zero.

Method 2: Place a Canary on the Stack

Insert a known random value (canary) in each function's stack frame; verify it on return. GCC supports this via -fstack-protector-all (all functions) or -fstack-protector-strong (functions with arrays or address-taken variables). The canary sits between local arrays and the saved frame pointer/return address. An overflow hits the canary first, triggering __stack_chk_fail() before the return address is corrupted.

void parse_frame(uint8_t *buf, uint32_t len) {
    uint8_t local[128];
    memcpy(local, buf, len);  /* len = 140, overflows */
    ...
}  /* return-time canary check: already 0xCDCDCDCD, trap */

Advantage: catches overflow in the offending function , not later. Cost: 5-10% code size increase with -fstack-protector-all; -fstack-protector-strong offers better trade-off. On embedded, implement __stack_chk_fail to log context and reset instead of aborting.

Method 3: MPU Guard Region

Cortex-M3/M4/M7 MPU can define regions with access permissions. Configure a 32-byte region just below the stack bottom as no-access. Any write crossing the boundary triggers a MemManage fault at the exact instruction , before any data is corrupted.

/* Stack bottom minus 32 bytes, no access */
MPU->RNR  = 1;
MPU->RBAR = (uint32_t)(stack_bottom - 32) & MPU_RBAR_ADDR_MASK;
MPU->RASR = (0x04 << MPU_RASR_SIZE_Pos)  /* 32 bytes */
         | MPU_RASR_B_Msk
         | (0 << MPU_RASR_AP_Pos);        /* no access */
MPU->CTRL = MPU_CTRL_ENABLE_Msk | MPU_CTRL_PRIVDEFENA_Msk;

MPU constraints:

Limited regions (typically 8); one consumed for stack guard.

Region size must be power of two (32, 64, 128...); cannot protect 24 bytes.

Base address must align to region size.

Only protects stack bottom (downward growth), not stack top.

Method 4: Isolate Stack in Separate RAM

Some MCUs have multiple RAM banks (e.g., RAM1, RAM2). Place stack in RAM2, data in RAM1. Physical separation ensures stack growth cannot corrupt data. Most thorough, but hardware-dependent. Stack can still overflow within RAM2, corrupting other RAM2 contents.

Method 5: Post-Reset Register Forensics

When prevention fails, analyze CPU registers after HardFault. The CPU automatically pushes 8 words (R0-R3, R12, LR, PC, xPSR) onto the stack. The HardFault handler must:

Read LR to determine which stack was active: 0xFFFFFFF9 → MSP, 0xFFFFFFFD → PSP (RTOS), 0xFFFFFFF1 → nested interrupt. Choosing the wrong stack loses the crash context.

Check CFSR (Configurable Fault Status Register): MSTKERR: stack push during exception failed — signature of stack overflow (SP already illegal). MMARVALID + MMFAR: precise MemManage fault address. IMPRECISERR: delayed bus fault due to write buffer; address unreliable. UNALIGNED: unaligned access, often wild pointer.

Extract sp[6] (saved PC), map via .map or addr2line to source line.

void HardFault_Handler(void) {
    __asm volatile (
        "tst lr, #4        
"
        "ite eq            
"
        "mrseq r0, msp     
"
        "mrsne r0, psp     
"
        "b hardfault_c     
"
    );
}

void hardfault_c(uint32_t *sp) {
    uint32_t cfsr = SCB->CFSR;
    /* sp[0..3]=r0-r3; sp[4]=r12; sp[5]=lr; sp[6]=pc; sp[7]=xpsr */
    save_to_backup(cfsr, sp[6], sp[7]);  /* backup registers survive reset */
    while (1);
}

Combining the Layers

Development: -fstack-protector-strong + sentinel watermark. Canary catches single overflows; watermark shows overall headroom.

Testing: Enable MPU stack-bottom guard. Intentionally stress stack depth; a trigger means insufficient margin.

Production: Disable -fstack-protector (save code size), keep sentinel watermark and HardFault backup logging. On field failure, recover context from backup registers after reset.

Critical Numbers to Calculate

Stack depth = deepest call chain × per-frame size + interrupt nesting + library overhead.

Interrupt nesting is often overlooked. Example: 1 KB stack, main loop uses 400 bytes. An interrupt adds 100 bytes, calls printf ( vsnprintf adds 200 bytes), another interrupt nests — suddenly at limit.

Real call-chain measurement: main 32, parse_frame 152, memcpy 24, vsnprintf 328, interrupt push 104 = 640 bytes. Remaining 384 looks safe, but this is best-case . Slightly more format args or one more nest exhausts margin.

Stack adequacy depends on the innermost layer, not the outermost.

Library stack usage must be measured: printf 100-500 bytes, malloc internal recursion, floating-point formatting, qsort recursion depth.

Reserve 30% margin, not 10% — you cannot test all paths.

Stack overflow is the hardest embedded bug to debug because the cause-effect chain is long: one out-of-bounds write may surface hundreds of milliseconds later as an unrelated symptom. Enable detection while coding, so it fails on your bench, not in the customer's hands.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

debuggingstack-overflowembedded-systemsmemory-protectionCortex-MMPUHardFaultstack-canary

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion