
Memory corruption is the nightmare that wakes embedded engineers at 3 AM. Your firmware runs for hours, then crashes in a completely unrelated function. The stack trace shows a null pointer dereference in printf, but printf worked fine yesterday. The bug is not in printf — something overwrote a function pointer, a vtable, or a task control block hours earlier.
This article covers practical, on-target techniques to catch memory corruption where it happens, not where it crashes. We focus on Cortex-M hardware features available on STM32, NXP, TI, and other MCUs: hardware watchpoints, stack canaries, and MPU guard regions.
Memory corruption separates into two distinct events separated in time and code location:
+--------------------------------------------------------------------+| MEMORY CORRUPTION TIMELINE |+--------------------------------------------------------------------+| || T=0 T=1hr T=5hr T=5hr+1ms || |-------------|-------------|------------| || | | | | || v v v v || +------+ +-------+ +-------+ +-------+ || |Buffer| |Buffer | |Buffer | | CRASH | || |Overflow|-->|Corrupts|--> |Unused | |in | || |Write | |Function| |Memory | |unrelated| || +------+ |Pointer | | | |function| || +-------+ +-------+ +-------+ || || The write and crash are separated in time and code location. || Debugging the crash site alone will never find the root cause. |+--------------------------------------------------------------------+
The debugger shows you the crash site. You need to catch the write.
| Pattern | Typical Cause | Corrupts | Manifestation |
|---|---|---|---|
| Buffer overflow | Missing bounds check, strcpy/memcpy | Adjacent globals, heap metadata | Crash in unrelated function |
| Use-after-free | free() then access, double-free | Heap allocator metadata, next allocation | Crash in malloc/free |
| Stack overflow | Large locals, deep recursion, ISR nesting | Heap, globals, other task stacks | Random hard fault |
| Integer overflow | Size calculation wraps | Allocation size, array index | Buffer overflow downstream |
| Type punning / strict aliasing | float* cast to uint32_t* | Compiler assumes no alias, optimizes wrong | Silent logic error |
| Unaligned access | uint32_t* cast from uint8_t* | Bus fault on Cortex-M0/M3 without alignment support | Immediate crash |
Each pattern requires a slightly different detection strategy, but all share the same root problem: the write happens at T, the crash at T+Δ.
Hardware watchpoints are the single most effective tool for memory corruption. They use dedicated comparator registers in the debug unit (DWT on Cortex-M) to monitor an address range. When any instruction writes to that address, the CPU halts at that instruction — zero software overhead, no timing perturbation.
Cortex-M3/M4/M7/M33 implement watchpoints through the Data Watchpoint and Trace (DWT) unit. The DWT provides 2-4 comparators (typically 4) that can each monitor an address or address range. When a data access matches, the DWT generates a debug event — halting the core if a debugger is attached, or triggering a debug monitor exception if configured.
+--------------------------------------------------------------------+| DWT WATCHPOINT ARCHITECTURE |+--------------------------------------------------------------------+| || CPU Core || +----------------+ || | Load/Store Unit| || +-------+--------+ || | Address + Data || v || +-------+--------+ Match? +-------------------+ || | DWT Comparators |----------------->| Debug Event | || | (COMP0..COMP3) | (addr match) | (Halt / Exception)| || +------------------+ +-------------------+ || | | | | || | | | +-- COMP0: Address + Mask/Range || | | +------- COMP1: Address + Mask/Range || | +---------- COMP2: Address + Mask/Range || +------------- COMP3: Address + Mask/Range || || Each comparator: 32-bit address + 4-bit mask (power-of-2 range) || Supports: read watch, write watch, read/write watch, PC match |+--------------------------------------------------------------------+
// Example: UART RX buffer overflow corrupting adjacent config struct#define UART_RX_BUF_SIZE 256static uint8_t uart_rx_buf[UART_RX_BUF_SIZE];static volatile uint16_t uart_rx_head = 0;static volatile uint16_t uart_rx_tail = 0;// Adjacent in memory — vulnerable to overflowstatic device_config_t device_config; // Gets corrupted when uart_rx_head wraps
# In GDB (via OpenOCD/J-Link):(gdb) break UART_IRQHandlerBreakpoint 1 at 0x8001234: file uart.c, line 45.(gdb) run...Breakpoint 1, UART_IRQHandler () at uart.c:45(gdb) watch *(uint8_t (*)[256])0x20001000 # Watch the entire bufferHardware watchpoint 2: *(uint8_t (*)[256])0x20001000(gdb) continue...Hardware watchpoint 2: *(uint8_t (*)[256])0x20001000Old value = {0x00 <repeats 256 times>}New value = {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x00 <repeats 251 times>} # Write at index 0(gdb) continue...Hardware watchpoint 2: *(uint8_t (*)[256])0x20001000Old value = {...}New value = {...} # Write at index 256 — OVERFLOW into device_config!(gdb) bt#0 UART_IRQHandler () at uart.c:52 <-- EXACT LINE CAUSING OVERFLOW
| Scenario | Watchpoint Strategy | GDB Command |
|---|---|---|
| Buffer overflow | Watch the byte after the buffer (&buf[SIZE]) | watch *0x20001100 |
| Use-after-free | Watch the freed pointer address after free() | watch *ptr after free |
| Stack overflow | Watch the stack guard region (see MPU section) | watch *0x20008000 |
| Function pointer corruption | Watch the function pointer variable directly | watch *0x20002000 |
| Global variable corruption | Watch the variable address | watch device_config.field |
| Heap metadata corruption | Watch malloc free list pointers | watch *heap_struct.next |
Limitation: Cortex-M typically provides 4 hardware watchpoints (DWT comparators). Use them strategically — watch boundaries, not entire arrays. One watchpoint on a buffer boundary catches all overflows.
// Watch the guard byte after a critical buffer#define CANARY_VALUE 0xDEADBEEFstatic uint32_t stack_canary __attribute__((section(".stack_canary"))) = CANARY_VALUE;// In GDB:(gdb) watch *0x20008000 // Address of stack_canary// CPU halts when canary is overwritten
GDB supports conditional watchpoints to reduce noise:
# Only halt when specific value written (e.g., null pointer)(gdb) watch *0x20001234(gdb) condition 2 *0x20001234 == 0# Only halt when written by specific function (via $pc)(gdb) condition 2 $pc >= 0x8001000 && $pc <= 0x8002000
Note: Conditional watchpoints evaluate in software after the hardware triggers, so they still halt briefly — but reduce manual resume cycles.
Stack overflow is a special case of memory corruption where the stack grows into adjacent memory (heap, globals, or another task stack). The crash happens when the overflow corrupts something critical — but the overflow started much earlier.
// linker script: place canary at stack boundary/* In .ld file */_stack_top = ORIGIN(RAM) + LENGTH(RAM);_stack_canary = _stack_top - 4;_stack_limit = _stack_canary - _stack_size;/* In startup code or main() */#define STACK_CANARY_VAL 0xDEADBEEFextern uint32_t _stack_canary;void stack_canary_init(void) {_stack_canary = STACK_CANARY_VAL;}// Periodic check (in SysTick, idle task, or watchdog ISR)bool stack_canary_check(void) {return _stack_canary == STACK_CANARY_VAL;}// In hard fault handler — check canary firstvoid HardFault_Handler(void) {if (_stack_canary != STACK_CANARY_VAL) {// STACK OVERFLOW DETECTED — log and haltlog_fault("STACK_OVERFLOW", __get_MSP());while (1) { __asm("bkpt #0"); }}// ... normal fault handling}
FreeRTOS and Zephyr provide built-in stack watermark checking:
// FreeRTOS: check per-task stack high-water markUBaseType_t hwm = uxTaskGetStackHighWaterMark(task_handle);// hwm = minimum free stack words remaining since task creation// If hwm == 0, stack has overflowed (or nearly so)// FreeRTOS v10+: configSTACK_DEPTH_TYPE for larger stacksconfigSTACK_DEPTH_TYPE hwm2 = uxTaskGetStackHighWaterMark2(task_handle);// Returns bytes on 32-bit, words on 16/8-bit// Zephyr: similar APIsize_t unused = k_thread_stack_space_get(thread_id);// Returns unused stack bytes
Pro tip: Enable stack overflow detection in FreeRTOS (configCHECK_FOR_STACK_OVERFLOW = 2). It fills the stack with a pattern at task creation and checks it on every context switch — catches overflow at the next context switch, not at crash time.
GCC/Clang -fstack-protector-strong inserts canaries automatically:
# Protects functions with:# - Local arrays of any size# - Local structs/unions containing arrays# - Functions calling alloca()# - Functions with address-taken local variablesCFLAGS += -fstack-protector-strong# Stronger: protect ALL functions (higher overhead)CFLAGS += -fstack-protector-all
The compiler places a canary between local variables and the saved frame pointer/return address. On function exit, it verifies the canary — if corrupted, calls __stack_chk_fail (implement this to log and halt).
+--------------------------------------------------------------------+| MEMORY LAYOUT WITH CANARIES |+--------------------------------------------------------------------+| || HIGH ADDRESS || +------------------+ || | STACK (grows | <-- Stack pointer moves DOWN || | down) | || +------------------+ || | CANARY (0xDEADBEEF)| <-- Guard region (4-16 bytes) || +------------------+ || | HEAP / GLOBALS | <-- Protected region || | (or next task) | || +------------------+ || LOW ADDRESS || || If stack grows past canary -> canary corrupted -> detected |+--------------------------------------------------------------------+
+--------------------------------------------------------------------+| RTOS TASK STACK LAYOUT |+--------------------------------------------------------------------+| || RAM || +------------------------+ 0x20020000 || | Task A Stack (4KB) | || | ... | || | Canary (0xDEADBEEF) | <- Task A stack limit || +------------------------+ || | Task B Stack (2KB) | || | ... | || | Canary (0xDEADBEEF) | <- Task B stack limit || +------------------------+ || | Heap | || | ... | || +------------------------+ || | Globals / .bss | || +------------------------+ || || FreeRTOS MPU port: reconfigures Region 6 on context switch || to protect current task's stack guard region. |+--------------------------------------------------------------------+
The Memory Protection Unit (MPU) on Cortex-M3/M4/M7/M33/M55 provides hardware-enforced memory access control. Unlike watchpoints (debug-only, halt CPU), MPU regions prevent illegal accesses in production — generating a MemManage fault instead of silently corrupting memory.
| Feature | ARMv7-M (Cortex-M3/M4/M7) | ARMv8-M Main (Cortex-M33/M55) |
|---|---|---|
| Region registers | RBAR + RASR (2 regs) | RBAR + RLAR (2 regs) |
| Size encoding | 5-bit size field (2^(N+1)) | Limit address + base |
| Subregions | 8 subregions per region | No subregions |
| Max regions | 8 or 16 | 8, 16, or 24 |
| Execute Never (XN) | Bit in RASR | Bit in RLAR |
// Cortex-M MPU setup for stack/heap guards// Requires: ARMv7-M or ARMv8-M Mainline (Cortex-M3/M4/M7/M33/M55)#include <stdint.h>#define MPU_BASE 0xE000ED90#define MPU_TYPE 0xE000ED90#define MPU_CTRL 0xE000ED94#define MPU_RNR 0xE000ED98#define MPU_RBAR 0xE000ED9C#define MPU_RLAR 0xE000EDA0 // ARMv8-M (RLAR) or RASR (ARMv7-M)// Region attributes#define MPU_RGN_ENABLE (1 << 0)#define MPU_RGN_PRIV_RW (0x3 << 1) // AP = 011: Priv RW, User RW#define MPU_RGN_PRIV_RO (0x5 << 1) // AP = 101: Priv RO, User RO#define MPU_RGN_NO_ACCESS (0x0 << 1) // AP = 000: No access#define MPU_RGN_XN (1 << 28) // Execute Never#define MPU_RGN_SIZE_32B (4 << 1) // 32 bytes (ARMv8-M: log2(size)-1)#define MPU_RGN_SIZE_64B (5 << 1)#define MPU_RGN_SIZE_128B (6 << 1)#define MPU_RGN_SIZE_256B (7 << 1)#define MPU_RGN_SIZE_512B (8 << 1)#define MPU_RGN_SIZE_1KB (9 << 1)static inline void mpu_write_rbar(uint32_t region, uint32_t addr) {*(volatile uint32_t*)MPU_RNR = region;*(volatile uint32_t*)MPU_RBAR = addr | MPU_RGN_ENABLE;}static inline void mpu_write_rlar(uint32_t region, uint32_t addr, uint32_t attr) {*(volatile uint32_t*)MPU_RLAR = (addr & ~0x1F) | attr;}void mpu_setup_guard_regions(void) {extern uint32_t _stack_top, _stack_limit, _heap_start, _heap_end;// Enable MPU with background region (privileged access to all memory)*(volatile uint32_t*)MPU_CTRL = 0x5; // ENABLE | PRIVDEFENA// Region 0: Stack guard (32 bytes below stack limit) - NO ACCESSuint32_t stack_guard_addr = (uint32_t)&_stack_limit - 32;mpu_write_rbar(0, stack_guard_addr);mpu_write_rlar(0, (uint32_t)&_stack_limit - 1,MPU_RGN_NO_ACCESS | MPU_RGN_XN | MPU_RGN_SIZE_32B);// Region 1: Heap guard (32 bytes after heap end) - NO ACCESSuint32_t heap_guard_addr = (uint32_t)&_heap_end;mpu_write_rbar(1, heap_guard_addr);mpu_write_rlar(1, (uint32_t)&_heap_end + 31,MPU_RGN_NO_ACCESS | MPU_RGN_XN | MPU_RGN_SIZE_32B);// Region 2: Null pointer guard (first 32 bytes of RAM) - NO ACCESS// Catches null pointer dereferencesmpu_write_rbar(2, 0x20000000); // Typical SRAM startmpu_write_rlar(2, 0x2000001F,MPU_RGN_NO_ACCESS | MPU_RGN_XN | MPU_RGN_SIZE_32B);// Region 3: Peripheral register region - Privileged only// Prevents user-mode code from touching hardware registersmpu_write_rbar(3, 0x40000000);mpu_write_rlar(3, 0x5FFFFFFF,MPU_RGN_PRIV_RW | MPU_RGN_XN); // Size covers all peripherals__DSB();__ISB();}
// ARMv7-M uses RASR instead of RLAR#define MPU_RASR 0xE000EDA0// RASR encoding: XN[28] AP[24:26] S[18] C[17] B[16] SRD[15:8] SIZE[1:5] ENABLE[0]#define MPU_RASR_NO_ACCESS_XN (1<<28 | 0<<24 | 0<<18 | 0<<17 | 0<<16 | 0<<8 | (5<<1) | 1) // 32B, no access, XNstatic inline void mpu_write_rasr(uint32_t region, uint32_t attr) {*(volatile uint32_t*)MPU_RNR = region;*(volatile uint32_t*)MPU_RASR = attr;}// Usage same as ARMv8-M but with RASR attributes
// When MPU violation occurs, MemManage fault triggersvoid MemManage_Handler(void) {uint32_t mmfar = *(volatile uint32_t*)0xE000ED34; // MemManage Fault Address Registeruint32_t cfsr = *(volatile uint32_t*)0xE000ED28; // Configurable Fault Status Registerbool mmar_valid = cfsr & (1 << 7); // MMARVALID bitlog_fault("MPU_VIOLATION", __get_MSP());log_fault_data("MMFAR", mmar_valid ? mmfar : 0);log_fault_data("CFSR", cfsr);// Decode CFSR bits:// Bit 0: IACCVIOL - Instruction access violation// Bit 1: DACCVIOL - Data access violation// Bit 3: MUNSTKERR - MemManage on unstacking// Bit 4: MSTKERR - MemManage on stacking// Bit 5: MLSPERR - MemManage during lazy FPU state preservationwhile (1) { __asm("bkpt #0"); }}
+--------------------------------------------------------------------+| MPU REGION ALLOCATION |+--------------------------------------------------------------------+| || Cortex-M typically provides 8 or 16 MPU regions. || Allocate strategically: || || Region 0: Null pointer guard (32B at 0x20000000) || Region 1: Stack guard (32B below stack limit) || Region 2: Heap guard (32B after heap end) || Region 3: Critical globals guard (config, keys, crypto) || Region 4: Peripheral space (privileged only) || Region 5: Flash/code region (execute only, no data write) || Region 6: Task stack guard (RTOS: reconfigure on context switch)|| Region 7: Free / application-specific || || RTOS context switch: reprogram Region 6 for new task stack || FreeRTOS MPU port does this automatically with || configUSE_MPU_WRAPPERS_V1 and xMPU_SETTINGS. |+--------------------------------------------------------------------+
// Place critical config in dedicated section__attribute__((section(".critical_config")))device_config_t active_config;// In linker script:/* .critical_config : { *(.critical_config) } > RAM */// MPU region for critical config (read-only after init)uint32_t config_start = (uint32_t)&__critical_config_start__;uint32_t config_end = (uint32_t)&__critical_config_end__;mpu_write_rbar(3, config_start);mpu_write_rlar(3, config_end - 1,MPU_RGN_PRIV_RO | MPU_RGN_XN | /* size attr */);// After init, make read-only:// mpu_update_region(3, MPU_RGN_PRIV_RO | ...);
Before hardware techniques, enable compiler protections that catch entire classes of bugs:
# GCC/Clang hardening flags for embeddedCFLAGS += \-fstack-protector-strong \ # Stack canaries on vulnerable functions-fstack-clash-protection \ # Probe stack on large allocations-D_FORTIFY_SOURCE=2 \ # Buffer overflow checks for libc functions-Wall -Wextra -Wpedantic \ # All warnings-Werror=implicit-function-declaration \-Werror=incompatible-pointer-types \-Werror=int-conversion \-Wshadow \ # Variable shadowing-Wdouble-promotion \ # Implicit float->double-fno-common \ # No tentative definitions-fstrict-aliasing \ # Enable strict aliasing optimizations-Wstrict-aliasing=2 # Warn on potential violations-Warray-bounds \ # Array bounds checking (GCC 12+)-Wstringop-overflow \ # String operation overflow (GCC 8+)-ftrivial-auto-var-init=pattern \ # Initialize auto vars (Clang/GCC 12+)
| Flag | Catches | Overhead |
|---|---|---|
-fstack-protector-strong | Stack buffer overflow in functions with local arrays/structs | ~2% code size |
-D_FORTIFY_SOURCE=2 | strcpy, memcpy, sprintf overflows at compile + runtime | Minimal |
-Wstrict-aliasing=2 | Type-punning violations (casting float* to uint32_t*) | Compile-time only |
-fno-common | Multiple tentative definitions of same global variable | Compile-time only |
-Wshadow | Local variable hiding global — common source of bugs | Compile-time only |
-ftrivial-auto-var-init=pattern | Uninitialized stack variables (init to 0xAA pattern) | Small runtime |
-fstack-clash-protection | Stack clash attacks, large frame allocations | Small runtime |
Note: -fstack-protector-strong adds a canary check in function prologue/epilogue. It protects functions with:
alloca()-fstack-protector-strong in Actionvoid vulnerable_function(char *input) {char buf[64]; // Protected by stack canarystrcpy(buf, input); // Overflow -> __stack_chk_fail}// Compiled with -fstack-protector-strong:// 1. Prologue: writes canary to stack// 2. Body: strcpy may overflow// 3. Epilogue: checks canary, calls __stack_chk_fail if corrupted
When you encounter a mysterious crash, follow this sequence:
+--------------------------------------------------------------------+| MEMORY CORRUPTION DEBUG WORKFLOW |+--------------------------------------------------------------------+| || 1. CRASH OCCURS || | || v || 2. CHECK HARD FAULT REGISTERS || - PC, LR, CFSR, BFAR, MMFAR || - Is it MemManage? -> MPU violation (good, caught early!) || - Is it BusFault? -> Invalid address / alignment || - Is it UsageFault? -> Undefined instr, div0, unaligned || | || v || 3. IS CRASH SITE OBVIOUSLY WRONG? || (null ptr in printf, bad vtable, corrupt task struct) || | || +-- YES --> SUSPECT MEMORY CORRUPTION || | || v || 4. IDENTIFY CORRUPTED OBJECT || - Function pointer? Task stack? Global config? Buffer? || | || v || 5. SET HARDWARE WATCHPOINT ON CORRUPTED ADDRESS || - Watch the exact address that was corrupted || - Or watch boundary of suspected buffer || | || v || 6. RUN UNTIL WATCHPOINT TRIGGERS || - CPU halts at EXACT instruction doing the bad write || - Examine call stack, registers, variables || | || v || 7. FIX ROOT CAUSE || - Buffer bounds check? Use-after-free? Stack overflow? || - Add canary/MPU guard to prevent recurrence || | || v || 8. VERIFY FIX || - Run stress test with watchpoint still set || - Enable MPU guards in production build || - Deploy with stack canary checking enabled |+--------------------------------------------------------------------+
// Minimal hard fault handler for debuggingvoid HardFault_Handler(void) {uint32_t *stack = (uint32_t*)__get_MSP(); // or PSP// Stacked registers (ARMv7-M/ARMv8-M):// stack[0] = R0, stack[1] = R1, stack[2] = R2, stack[3] = R3// stack[4] = R12, stack[5] = LR, stack[6] = PC, stack[7] = xPSRuint32_t pc = stack[6];uint32_t lr = stack[5];uint32_t cfsr = *(volatile uint32_t*)0xE000ED28;uint32_t hfsr = *(volatile uint32_t*)0xE000ED2C;uint32_t bfar = *(volatile uint32_t*)0xE000ED38; // BFARVALID in CFSR bit 15uint32_t mmfar= *(volatile uint32_t*)0xE000ED34; // MMARVALID in CFSR bit 7log_fault("HARD_FAULT", pc);log_fault_data("LR", lr);log_fault_data("CFSR", cfsr);log_fault_data("HFSR", hfsr);if (cfsr & (1<<15)) log_fault_data("BFAR", bfar);if (cfsr & (1<<7)) log_fault_data("MMFAR", mmfar);// Look up PC in .map file or addr2linewhile (1) { __asm("bkpt #0"); }}
// uart.c#define UART_RX_BUF_SIZE 128static uint8_t rx_buf[UART_RX_BUF_SIZE];static volatile uint16_t rx_head = 0;static volatile uint16_t rx_tail = 0;// In same .bss section, adjacent to rx_buf:static device_config_t active_config; // Gets corrupted!void UART_IRQHandler(void) {if (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_RXNE)) {uint8_t data = (uint8_t)(huart1.Instance->DR & 0xFF);rx_buf[rx_head] = data; // NO BOUNDS CHECK!rx_head = (rx_head + 1) % UART_RX_BUF_SIZE; // Modulo hides overflow}}
Under heavy load, interrupts fire faster than the main loop processes data. rx_head wraps, but the modulo makes it look correct. The write at index 128 lands in active_config.
// Fix 1: Bounds check with overflow flagvoid UART_IRQHandler(void) {if (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_RXNE)) {uint8_t data = (uint8_t)(huart1.Instance->DR & 0xFF);uint16_t next_head = (rx_head + 1) % UART_RX_BUF_SIZE;if (next_head != rx_tail) { // Buffer not fullrx_buf[rx_head] = data;rx_head = next_head;} else {uart_overflow_flag = true; // Signal main loop// Option: drop oldest, or drop newest}}}// Fix 2: MPU guard region after rx_buf (in mpu_setup_guard_regions)uint32_t rx_buf_end = (uint32_t)&rx_buf[UART_RX_BUF_SIZE];mpu_write_rbar(2, rx_buf_end);mpu_write_rlar(2, rx_buf_end + 31, MPU_RGN_NO_ACCESS | MPU_RGN_XN | MPU_RGN_SIZE_32B);// Fix 3: Compiler hardening// -fstack-protector-strong catches stack buffers// -D_FORTIFY_SOURCE=2 would catch memcpy/strcpy into rx_buf
# GDB session(gdb) watch *0x20001080 # Address of active_config(gdb) continue# Triggers at rx_buf[rx_head] = data when rx_head == 128# bt shows UART_IRQHandler line 12
| Technique | Development | Production |
|---|---|---|
| Hardware watchpoints | Primary tool | Not available (no debugger) |
| Stack canaries (compiler) | Enabled | Enabled (-fstack-protector-strong) |
| Stack canaries (RTOS) | Enabled | Enabled (configCHECK_FOR_STACK_OVERFLOW=2) |
| MPU guard regions | Enabled | Enabled — zero overhead |
| Null pointer guard (MPU) | Enabled | Enabled |
| Heap/stack guards (MPU) | Enabled | Enabled |
| AddressSanitizer | Host tests only | Not applicable |
Key insight: MPU guards and compiler-inserted canaries have near-zero runtime cost and work in production without a debugger. They transform silent memory corruption into immediate, diagnosable faults.
# CMake exampletarget_compile_options(firmware PRIVATE-fstack-protector-strong-fstack-clash-protection-D_FORTIFY_SOURCE=2-Wall -Wextra -Wpedantic-Werror=implicit-function-declaration-Werror=incompatible-pointer-types-Werror=int-conversion-Wshadow-Wstrict-aliasing=2-fno-common-ftrivial-auto-var-init=pattern)# Linker script: define guard symbols_stack_top = ORIGIN(RAM) + LENGTH(RAM);_stack_canary = _stack_top - 4;_stack_limit = _stack_canary - _stack_size;_heap_end = ...;
Memory corruption bugs are characterized by a gap between cause and symptom. The corruption write happens at time T, the crash at T+Δ. Traditional debugging examines the crash site — you must instead catch the write.
Tool hierarchy for embedded C:
-fstack-protector-strong, -D_FORTIFY_SOURCE=2) — catches bugs at compile time and runtime, zero hardware costStart with compiler flags. They catch 80% of buffer overflows and stack smashes with one line in CMake. Add RTOS stack checking. For the rest — intermittent, production-only corruption — deploy MPU guards on critical boundaries (stack, heap, null pointer, config structs). When a MemManage fault fires, the fault address tells you exactly what was accessed illegally.
The best debug session is the one you never have because the MPU caught it in production and logged the fault address before the device shipped.
Quick Links
Legal Stuff





