HomeAbout UsContact Us

Fixing Embedded C Memory Corruption: Watchpoints, Canaries

By Jithin Tom
Published in Embedded C/C++
November 23, 2026
4 min read
Fixing Embedded C Memory Corruption: Watchpoints, Canaries

Table Of Contents

01
The Core Problem: Symptom vs. Cause
02
Hardware Watchpoints: Catch the Exact Write
03
Stack Canaries: Detect Stack Growth Before Crash
04
MPU Guard Regions: Continuous Production Protection
05
Compiler Hardening: Catch Bugs at Compile Time
06
Complete Debugging Workflow
07
Real-World Example: UART Buffer Overflow Corrupting Config
08
Production Deployment Strategy
09
Summary
10
Related Reading
11
References
12
Frequently Asked Questions

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.

The Core Problem: Symptom vs. Cause

Memory corruption separates into two distinct events separated in time and code location:

  • The write — an out-of-bounds buffer access, use-after-free, stack overflow, or integer overflow writes to an address it should not touch
  • The crash — much later, the corrupted data (a function pointer, task stack pointer, interrupt vector, vtable entry, or RTOS queue pointer) is used, triggering a hard fault, bus fault, usage fault, or silent logic error
+--------------------------------------------------------------------+
| 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.

Common Corruption Patterns in Embedded C

PatternTypical CauseCorruptsManifestation
Buffer overflowMissing bounds check, strcpy/memcpyAdjacent globals, heap metadataCrash in unrelated function
Use-after-freefree() then access, double-freeHeap allocator metadata, next allocationCrash in malloc/free
Stack overflowLarge locals, deep recursion, ISR nestingHeap, globals, other task stacksRandom hard fault
Integer overflowSize calculation wrapsAllocation size, array indexBuffer overflow downstream
Type punning / strict aliasingfloat* cast to uint32_t*Compiler assumes no alias, optimizes wrongSilent logic error
Unaligned accessuint32_t* cast from uint8_t*Bus fault on Cortex-M0/M3 without alignment supportImmediate 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: Catch the Exact Write

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.

How DWT Watchpoints Work

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 |
+--------------------------------------------------------------------+

Setting Watchpoints in GDB

// Example: UART RX buffer overflow corrupting adjacent config struct
#define UART_RX_BUF_SIZE 256
static 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 overflow
static device_config_t device_config; // Gets corrupted when uart_rx_head wraps
# In GDB (via OpenOCD/J-Link):
(gdb) break UART_IRQHandler
Breakpoint 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 buffer
Hardware watchpoint 2: *(uint8_t (*)[256])0x20001000
(gdb) continue
...
Hardware watchpoint 2: *(uint8_t (*)[256])0x20001000
Old 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])0x20001000
Old value = {...}
New value = {...} # Write at index 256 — OVERFLOW into device_config!
(gdb) bt
#0 UART_IRQHandler () at uart.c:52 <-- EXACT LINE CAUSING OVERFLOW

Watchpoint Best Practices

ScenarioWatchpoint StrategyGDB Command
Buffer overflowWatch the byte after the buffer (&buf[SIZE])watch *0x20001100
Use-after-freeWatch the freed pointer address after free()watch *ptr after free
Stack overflowWatch the stack guard region (see MPU section)watch *0x20008000
Function pointer corruptionWatch the function pointer variable directlywatch *0x20002000
Global variable corruptionWatch the variable addresswatch device_config.field
Heap metadata corruptionWatch malloc free list pointerswatch *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.

Watchpoint Setup for Buffer Boundaries

// Watch the guard byte after a critical buffer
#define CANARY_VALUE 0xDEADBEEF
static 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

Advanced: Watchpoint Conditions

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 Canaries: Detect Stack Growth Before Crash

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.

Canary Pattern Implementation

// 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 0xDEADBEEF
extern 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 first
void HardFault_Handler(void) {
if (_stack_canary != STACK_CANARY_VAL) {
// STACK OVERFLOW DETECTED — log and halt
log_fault("STACK_OVERFLOW", __get_MSP());
while (1) { __asm("bkpt #0"); }
}
// ... normal fault handling
}

RTOS Task Stack Canaries

FreeRTOS and Zephyr provide built-in stack watermark checking:

// FreeRTOS: check per-task stack high-water mark
UBaseType_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 stacks
configSTACK_DEPTH_TYPE hwm2 = uxTaskGetStackHighWaterMark2(task_handle);
// Returns bytes on 32-bit, words on 16/8-bit
// Zephyr: similar API
size_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.

Compiler-Inserted Stack Canaries

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 variables
CFLAGS += -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).

Canary Placement Strategy

+--------------------------------------------------------------------+
| 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 |
+--------------------------------------------------------------------+

Multi-Task Stack Layout (RTOS)

+--------------------------------------------------------------------+
| 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. |
+--------------------------------------------------------------------+

MPU Guard Regions: Continuous Production Protection

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.

ARMv7-M vs ARMv8-M MPU Differences

FeatureARMv7-M (Cortex-M3/M4/M7)ARMv8-M Main (Cortex-M33/M55)
Region registersRBAR + RASR (2 regs)RBAR + RLAR (2 regs)
Size encoding5-bit size field (2^(N+1))Limit address + base
Subregions8 subregions per regionNo subregions
Max regions8 or 168, 16, or 24
Execute Never (XN)Bit in RASRBit in RLAR

MPU Configuration for Guard Regions (ARMv8-M)

// 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 ACCESS
uint32_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 ACCESS
uint32_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 dereferences
mpu_write_rbar(2, 0x20000000); // Typical SRAM start
mpu_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 registers
mpu_write_rbar(3, 0x40000000);
mpu_write_rlar(3, 0x5FFFFFFF,
MPU_RGN_PRIV_RW | MPU_RGN_XN); // Size covers all peripherals
__DSB();
__ISB();
}

ARMv7-M Variant (Cortex-M3/M4/M7)

// 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, XN
static 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

MemManage Fault Handler

// When MPU violation occurs, MemManage fault triggers
void MemManage_Handler(void) {
uint32_t mmfar = *(volatile uint32_t*)0xE000ED34; // MemManage Fault Address Register
uint32_t cfsr = *(volatile uint32_t*)0xE000ED28; // Configurable Fault Status Register
bool mmar_valid = cfsr & (1 << 7); // MMARVALID bit
log_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 preservation
while (1) { __asm("bkpt #0"); }
}

MPU Region Allocation Strategy

+--------------------------------------------------------------------+
| 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. |
+--------------------------------------------------------------------+

Protecting Critical Global Data

// 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 | ...);

Compiler Hardening: Catch Bugs at Compile Time

Before hardware techniques, enable compiler protections that catch entire classes of bugs:

# GCC/Clang hardening flags for embedded
CFLAGS += \
-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+)

What Each Flag Catches

FlagCatchesOverhead
-fstack-protector-strongStack buffer overflow in functions with local arrays/structs~2% code size
-D_FORTIFY_SOURCE=2strcpy, memcpy, sprintf overflows at compile + runtimeMinimal
-Wstrict-aliasing=2Type-punning violations (casting float* to uint32_t*)Compile-time only
-fno-commonMultiple tentative definitions of same global variableCompile-time only
-WshadowLocal variable hiding global — common source of bugsCompile-time only
-ftrivial-auto-var-init=patternUninitialized stack variables (init to 0xAA pattern)Small runtime
-fstack-clash-protectionStack clash attacks, large frame allocationsSmall runtime

Note: -fstack-protector-strong adds a canary check in function prologue/epilogue. It protects functions with:

  • Local arrays of any size
  • Local structs/unions containing arrays
  • Functions calling alloca()
  • Functions with address-taken local variables

Example: -fstack-protector-strong in Action

void vulnerable_function(char *input) {
char buf[64]; // Protected by stack canary
strcpy(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

Complete Debugging Workflow

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 |
+--------------------------------------------------------------------+

Hard Fault Register Decoding

// Minimal hard fault handler for debugging
void 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] = xPSR
uint32_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 15
uint32_t mmfar= *(volatile uint32_t*)0xE000ED34; // MMARVALID in CFSR bit 7
log_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 addr2line
while (1) { __asm("bkpt #0"); }
}

Real-World Example: UART Buffer Overflow Corrupting Config

The Bug

// uart.c
#define UART_RX_BUF_SIZE 128
static 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.

The Fix

// Fix 1: Bounds check with overflow flag
void 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 full
rx_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

Verification

# 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

Production Deployment Strategy

TechniqueDevelopmentProduction
Hardware watchpointsPrimary toolNot available (no debugger)
Stack canaries (compiler)EnabledEnabled (-fstack-protector-strong)
Stack canaries (RTOS)EnabledEnabled (configCHECK_FOR_STACK_OVERFLOW=2)
MPU guard regionsEnabledEnabled — zero overhead
Null pointer guard (MPU)EnabledEnabled
Heap/stack guards (MPU)EnabledEnabled
AddressSanitizerHost tests onlyNot 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.

Production Build Checklist

# CMake example
target_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 = ...;

Summary

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:

  1. Compiler hardening (-fstack-protector-strong, -D_FORTIFY_SOURCE=2) — catches bugs at compile time and runtime, zero hardware cost
  2. Hardware watchpoints — development only, catches exact write instruction, limited to 4 on Cortex-M
  3. Stack canaries (compiler + RTOS) — detects stack overflow before crash, works in production
  4. MPU guard regions — production-grade, hardware-enforced, prevents corruption entirely, generates MemManage fault at violation point

Start 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.

References

  1. ARM Limited, ARMv7-M Architecture Reference Manual, Section B3.5 “Memory Protection Unit”, 2020. Available: https://support.arm.com/documentation/ddi0403/latest
  2. ARM Limited, Cortex-M3/M4/M7 Devices Generic User Guide, Chapter 4 “Memory Protection Unit”, 2017. Available: https://support.arm.com/documentation/dui0553/latest
  3. FreeRTOS Kernel Documentation, Stack Overflow Detection, configCHECK_FOR_STACK_OVERFLOW. Available: https://www.freertos.org/Documentation/02-Kernel/04-API-references/03-Task-utilities/04-uxTaskGetStackHighWaterMark
  4. GCC Documentation, Instrumentation Options (-fstack-protector, -fstack-clash-protection). Available: https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html
  5. LLVM/Clang Documentation, AddressSanitizer and Hardening flags. Available: https://clang.llvm.org/docs/AddressSanitizer.html
  6. STMicroelectronics, STM32F4xx Reference Manual (RM0090), Section 4.3 “Memory Protection Unit”, 2023. Available: https://www.st.com/content/ccc/resource/technical/document/reference_manual/3d/6d/5a/66/b4/99/40/d4/DM00031020.pdf/files/DM00031020.pdf/jcr:content/translations/en.DM00031020.pdf

Frequently Asked Questions

What is the fastest way to find where memory corruption occurs in embedded C?

Hardware watchpoints are the fastest method — they halt the CPU the exact instruction that writes to a corrupted address, with zero runtime overhead. Set a watchpoint on the corrupted variable or buffer boundary using your debugger (GDB: `watch *0x20001234`), then run until the write occurs.

How do stack canaries detect stack overflow before a crash?

Stack canaries place a known pattern (e.g., 0xDEADBEEF) at the stack boundary. A periodic check or interrupt handler verifies the pattern remains intact. If overwritten, the canary detects stack growth beyond its limit before the overflow corrupts adjacent memory or causes a hard fault.

When should I use MPU guard regions instead of watchpoints?

Use MPU guard regions for continuous, zero-overhead protection in production firmware. Watchpoints are limited (typically 4 on Cortex-M) and halt the CPU — ideal for development. MPU guards can protect multiple regions simultaneously without stopping execution, making them suitable for deployed systems.

Can AddressSanitizer catch memory corruption on target hardware?

No — AddressSanitizer requires instrumented binaries and shadow memory, which only work on host (Linux/macOS/Windows) with mocked HAL. For on-target detection, use hardware watchpoints, MPU guards, stack canaries, or compiler hardening flags like `-fstack-protector-strong`.

Why does my firmware crash randomly with no clear pattern?

Random crashes often indicate memory corruption (buffer overflow, use-after-free, stack overflow) where the symptom appears far from the cause. The corruption overwrites a critical structure (task control block, interrupt vector, function pointer), and the crash occurs later when that corrupted data is used. Use watchpoints on suspected buffers to catch the exact write.

Tags

embedded-cdebuggingmemory-corruptioncortex-mwatchpointsstack-canariesmpu

Share


Previous Article
Fixing Rust HardFaults: Stack Overflow Detection with MSPLIM
Jithin Tom

Jithin Tom

A Closer Look at C/C++, RTOS, and Embedded Systems

Related Posts

Fixing C Integer Promotion Bugs on 8-bit and 16-bit MCUs
Fixing C Integer Promotion Bugs on 8-bit and 16-bit MCUs
November 19, 2026
14 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media