HomeAbout UsContact Us

Fixing Embedded C Memory Corruption: Watchpoints, Canaries, and MPU Guards

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

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 RX Overrun Corrupting Adjacent State
08
Production Deployment Matrix
09
Summary
10
Related Reading
11
References
12
Frequently Asked Questions

Firmware that appears to fail in an unrelated function may have experienced an earlier out-of-bounds write, use-after-free, stack overflow, or DMA misconfiguration. It can also fail for reasons unrelated to memory corruption. The fastest route to an explanation is to capture fault context, identify any damaged object, and instrument the suspected access.

This article explains on-target Cortex-M techniques for observing and preventing selected memory errors: DWT hardware watchpoints, boundary sentinels, compiler stack guards, RTOS watermarks and MPU-protected regions. The details depend on the core architecture, RTOS, debug configuration and memory map.

The Core Problem: Symptom vs. Cause

A memory-corruption bug and the failure it causes can be far apart in both time and source code. A bad pointer, an undersized allocation, or a stack crossing its allocated boundary may alter data that is not used until a much later interrupt or task activation.

  • The offending access: An out-of-bounds read/write, use-after-free, stack overrun, or another invalid access. Arithmetic overflow can lead to a bad allocation or index, but is not itself a memory write.
  • The observed failure: A delayed incorrect result, HardFault, MemManage or BusFault, or corrupted RTOS state. Some faults arise immediately at the invalid access; others do not.
+-----------------------------------------------------------------------+
| MEMORY CORRUPTION TIMELINE |
+-----------------------------------------------------------------------+
| |
| T0: Unsafe access |
| | |
| v |
| [Write outside allocated object] |
| | |
| v |
| [Other state is changed] |
| | Possibly minutes or hours |
| v |
| [Code later uses changed state] |
| | |
| v |
| [Wrong output / unexpected fault / reset] |
| |
| Goal: identify the writer, not just the eventual crash site. |
+-----------------------------------------------------------------------+

A fault backtrace is a useful starting point, not proof of where corruption began. Determine the damaged location and instrument that location to find the access responsible.

Common Corruption Patterns in Embedded C

PatternTypical causeWhat to investigate
Buffer overrunIncorrect index, unbounded copyArray size, object layout, parser lengths
Use-after-free / double-freeExpired ownership, allocator misuseAllocation lifetimes and heap metadata
Stack exhaustionLarge arrays, recursion, deep interrupt nestingMSP/PSP limits, per-thread stack usage
Integer overflowWrapped allocation-size or index calculationChecked multiplication/addition before allocation
Strict-aliasing violationAccess through an incompatible object pointerEffective types and compiler optimization
Unaligned accessAssumed pointer alignmentArchitecture, access width and CCR.UNALIGN_TRP
DMA overwriteIncorrect DMA length or cache-coherency handlingTransfer descriptors, actual bus masters

Not every case is a delayed write. For example, a misaligned access can fault immediately, and a strict-aliasing violation may yield wrong values without writing outside an object. CPU DWT watchpoints also may not observe DMA or other non-CPU bus-master writes.

Hardware Watchpoints: Catch the Exact Write

A hardware data watchpoint is often the fastest way to locate a CPU instruction accessing a known corrupted address. Its comparator normally runs without adding instrumentation instructions to application code, but a debug event occurs because of an access; the watchpoint is not a memory-protection barrier. Halting and probe interaction change system timing and can disturb real-time behavior.

When access is by DMA or another bus master, a CPU watchpoint may not fire. Use the SoC’s bus trace or peripheral diagnostics, or place an MPU guard on accesses the MPU can actually control.

How DWT Watchpoints Work

Many Cortex-M3/M4/M7 and Armv8-M Mainline cores provide a Data Watchpoint and Trace (DWT) unit. The number and capabilities of comparators are implementation dependent, and some parts omit or restrict them. On classic Armv7-M DWT implementations, a data watchpoint uses DWT_COMPn, DWT_MASKn and DWT_FUNCTIONn; the register model differs on some newer Armv8-M designs. Prefer the debugger’s hardware-watchpoint facility unless you have verified your particular core’s debug architecture.

+----------------------------------------------------------------------+
| CPU DATA WATCHPOINT |
+----------------------------------------------------------------------+
| |
| CPU load/store instruction |
| | |
| v |
| [Address and access type] |
| | |
| v |
| [DWT comparator matches?] |
| | |
| +----+----+ |
| | | |
| NO YES |
| | | |
| v v |
| Continue Debug event |
| | |
| +--> Debugger may halt CPU |
| +--> DebugMonitor on supported configurations |
| |
| This detects a matching CPU access; it is not a pre-write guard. |
+----------------------------------------------------------------------+

A DWT comparator does not universally identify the same source instruction on every device: the debugger’s reported program counter can point at or after the access, depending on implementation. Capture the instruction disassembly and surrounding context.

Setting Watchpoints in GDB

Suppose a UART buffer and a configuration object are held in one containing structure. This deliberately fixes their relative layout; two unrelated file-scope variables are not guaranteed to be adjacent.

#include <stdint.h>
typedef struct {
uint32_t magic_number;
uint32_t baud_rate;
} device_config_t;
typedef struct {
uint8_t rx[256];
device_config_t config;
} app_state_t;
static app_state_t app_state = {
.config = { .magic_number = 0x55AA1234u, .baud_rate = 115200u }
};

In a stopped GDB session, set a hardware write watchpoint on the field you know is becoming corrupted:

(gdb) target remote :3333
(gdb) monitor reset halt
(gdb) load
(gdb) watch -location app_state.config.magic_number
(gdb) info breakpoints
(gdb) continue
# When it stops:
(gdb) x/i $pc
(gdb) disassemble /m
(gdb) bt
(gdb) p/x app_state.config.magic_number

watch usually chooses a hardware watchpoint when the server supports the address and access size; check the GDB response rather than assuming. A range or large object may exhaust hardware comparator resources. A software watchpoint can instead single-step and radically perturb execution.

Do not form an invalid C pointer to &buf[SIZE] and dereference it in application code. In GDB you can watch an actual neighboring object or use an explicitly known RAM address and access width, for example watch *(uint32_t *)0x20001234 after verifying that address belongs to the desired object.

Direct Register-Level DWT Watchpoint Configuration

The following is an illustrative Armv7-M/CMSIS test helper, not a portable way to configure every Cortex-M DWT. It assumes a classic comparator-0 register layout, that the comparator is present and accessible, that debug/trace has been unlocked when required, and that the address is word aligned.

#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#include "core_cm4.h" /* Adapt to the actual Cortex-M core CMSIS header. */
bool dwt_v7m_watch_word_write(volatile uint32_t *word)
{
if (word == NULL || ((uintptr_t)word & 3u) != 0u) {
return false;
}
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
if ((DWT->CTRL & DWT_CTRL_NUMCOMP_Msk) == 0u) {
return false;
}
DWT->FUNCTION0 = 0u; /* Disable before reprogramming. */
DWT->COMP0 = (uint32_t)(uintptr_t)word;
DWT->MASK0 = 0u;
DWT->FUNCTION0 = 6u; /* Classic Armv7-M: data-write match. */
__DSB();
__ISB();
return true;
}

This function alone does not make an unattended fault logger. An attached debugger must enable/handle halting debug, or firmware must separately configure a supported DebugMonitor pathway and a safe handler. On some Cortex-M7 devices, the DWT Lock Access Register also needs unlocking. For Armv8-M, use the core-specific debug manual or debugger rather than copying MASK0/FUNCTION0 assumptions without checking.

Watchpoint Best Practices

Debug targetBetter watchpoint targetGDB example
Buffer overflowFirst known adjacent object fieldwatch -location app_state.config.magic_number
Heap corruptionA verified allocator metadata fieldwatch -location heap_header->size
Stack boundaryA dedicated canary objectwatch -location stack_canary_word
Function-pointer overwritePointer storagewatch -location callback_ptr
Global-variable clobberThe object being changedwatch -location g_system_state

A null dereference is usually investigated using fault status registers and an MPU, not by watching address zero: the address might contain an aliased vector table, and hardware watchpoints do not make invalid access safe. Check that the suspected writer is executed by the CPU; an external DMA engine can bypass the core’s DWT comparator.

Stack Canaries: Detect Stack Growth Before Crash

Stack-boundary canaries are sentinels, not hardware guards. They reveal that a reserved word has been overwritten when software checks the word, which may be after other memory was already damaged. A jump over the sentinel or a different overwrite path can escape detection. Compiler-inserted stack protectors address a different threat: overwrites of selected function frames detected when a protected function returns.

Linker Script Canary Placement

On a typical downward-growing Cortex-M stack, place a sentinel at the low-address end of an explicitly reserved stack area, and ensure the startup code actually initializes MSP from the matching top symbol. The linker excerpt below is illustrative: integrate it into the project’s existing memory map, reserve space for all other sections, and account for alignment and any RTOS/ISR stacks.

+----------------------------------------------------------------------+
| DOWNWARD-GROWING STACK AND SENTINEL |
+----------------------------------------------------------------------+
| |
| High address: initial MSP / _stack_top |
| +--------------------------------------------+ |
| | Reserved stack area | |
| | | | |
| | v Stack grows toward low RAM | |
| | | |
| +--------------------------------------------+ |
| | Sentinel word (checked periodically) | <- _stack_limit |
| +--------------------------------------------+ |
| | Other allocated RAM / separately guarded | |
| | area; DO NOT assume overwrites stop here. | |
| +--------------------------------------------+ |
| Low address |
| |
| Detects a crossed boundary only if the sentinel is altered. |
+----------------------------------------------------------------------+
/* Fragment for a project-specific GNU ld SECTIONS block. */
_stack_size = 0x1000; /* Example: 4 KiB reserved in total. */
._stack (NOLOAD) :
{
. = ALIGN(8);
_stack_limit = .; /* Lowest 4 bytes reserved as sentinel. */
. = . + _stack_size;
_stack_top = .; /* Initial MSP in the vector table. */
} > RAM
ASSERT((_stack_top - _stack_limit) == _stack_size,
"stack reservation must be exactly _stack_size bytes")
#include <stdbool.h>
#include <stdint.h>
#define STACK_CANARY_PATTERN UINT32_C(0xDEADBEEF)
extern uint32_t _stack_limit; /* Linker symbol; address is the sentinel. */
void stack_canary_init(void)
{
*(volatile uint32_t *)&_stack_limit = STACK_CANARY_PATTERN;
}
bool stack_canary_is_intact(void)
{
return *(volatile const uint32_t *)&_stack_limit == STACK_CANARY_PATTERN;
}

Initialize the sentinel after memory startup has established the linker layout and before deep calls. A stack-overflowing instruction can corrupt neighboring data before the next scheduled canary check; use an MPU guard or architectural stack limit to stop prohibited accesses.

RTOS Task Stack Watermarking

RTOS tasks commonly use distinct, downward-growing stacks. The main/interrupt MSP may be separate from a task’s PSP, so monitoring only _stack_limit cannot cover every stack.

+----------------------------------------------------------------------+
| EXAMPLE RTOS STACKS |
+----------------------------------------------------------------------+
| |
| Task A stack: [top] ----> grows down ----> [A low boundary] |
| Task B stack: [top] ----> grows down ----> [B low boundary] |
| ISR/MSP stack: [top] ----> grows down ----> [MSP boundary] |
| |
| Protect or monitor each allocated stack independently. |
| An RTOS watermark measures previous use, not guaranteed headroom. |
+----------------------------------------------------------------------+

FreeRTOS Built-In Detection

In FreeRTOS, configCHECK_FOR_STACK_OVERFLOW = 1 checks stack-pointer bounds during supported context-switch paths; mode 2 additionally checks whether a pattern at the low end of a task stack was overwritten. Details and sampled bytes are port/version dependent. These checks are not a substitute for an MPU guard and can miss an overrun that occurs between checks or jumps across the sentinel.

/* FreeRTOSConfig.h */
#define configCHECK_FOR_STACK_OVERFLOW 2
/* Application source: do not perform complex logging on a damaged stack. */
#include "FreeRTOS.h"
#include "task.h"
void vApplicationStackOverflowHook(TaskHandle_t task, char *task_name)
{
(void)task;
(void)task_name;
taskDISABLE_INTERRUPTS();
for (;;) {
/* Record a minimal failure indication using an established safe path. */
}
}

The high-water mark is computed by scanning the initial fill pattern and is a minimum-ever unused region estimate, not a real-time stack-pointer measurement; a stack that has overflowed and recovered cannot be trusted solely from this value.

UBaseType_t words = uxTaskGetStackHighWaterMark(task_handle);
size_t unused_bytes = (size_t)words * sizeof(StackType_t);
if (unused_bytes < 128u) {
report_low_stack_headroom(unused_bytes); /* Application-defined. */
}

Check which FreeRTOS kernel/port you use: some ports interpret stack-depth units differently, and stack checking introduces context-switch overhead.

Zephyr RTOS Thread Stack Space

Zephyr’s k_thread_stack_space_get() provides unused-stack estimates when both CONFIG_INIT_STACKS=y and CONFIG_THREAD_STACK_INFO=y are enabled. It scans the initialized region; it cannot prove that no out-of-bounds access occurred.

# prj.conf
CONFIG_INIT_STACKS=y
CONFIG_THREAD_STACK_INFO=y
#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>
void check_current_thread_stack(void)
{
size_t unused = 0;
int rc = k_thread_stack_space_get(k_current_get(), &unused);
if (rc == 0 && unused < 128u) {
printk("WARN: low thread stack watermark: %zu bytes\n", unused);
}
}

The measurement can be costly; call it from a suitable thread context and account for its limitations with protected/user-mode stacks.

Compiler-Inserted Stack Protectors (-fstack-protector)

-fstack-protector-strong instruments selected functions with a guard check, usually on function return. It helps detect some stack-buffer overwrites but does not implement general bounds checking, prevent the original write, or guarantee coverage of every function.

# Makefile example, for a toolchain with stack-protector support
CFLAGS += -fstack-protector-strong
# Use -fstack-protector-all only if its additional cost is acceptable.

For bare-metal toolchains, verify whether the runtime already provides __stack_chk_guard and __stack_chk_fail. Only define them if absent, and seed the guard with a device-appropriate unpredictable value before protected code runs when your threat model includes malicious input. The following static value is only a demonstration for debugging.

#include <stdint.h>
/* Example ONLY if the C runtime does not already provide these symbols. */
uintptr_t __stack_chk_guard = UINT32_C(0x595E9FBD);
__attribute__((noreturn)) void __stack_chk_fail(void)
{
__asm volatile ("cpsid i" ::: "memory"); /* Cortex-M example. */
for (;;) {
/* Minimal fault indication; avoid further stack-heavy calls. */
}
}

A stack-protector report identifies a protected function whose guard was changed, not necessarily the precise instruction that performed the bad write. If compiler libraries provide their own guard/failure handler, do not create duplicate definitions.

MPU Guard Regions: Continuous Production Protection

An MPU can enforce memory permissions without requiring an attached debugger. An access that violates the configured attributes can raise a MemManage fault (or escalate to HardFault if disabled or unavailable), but the fault is not guaranteed to be recoverable: the exception itself needs a valid stack. Guard placement, region precedence, privileged background access, DMA access paths, and RTOS MPU ownership must all be reviewed.

Unlike a watchpoint, a correctly configured MPU prevents an access forbidden by that region. It is not a blanket defense against every overrun: an access that jumps past the guard into another permitted address can still corrupt memory, and CPU MPUs do not necessarily protect DMA transactions.

ARMv7-M vs ARMv8-M PMSA Differences

FeatureArmv7-M MPU (M3/M4/M7)Armv8-M Mainline MPU (M33/M55/M85)
Region controlsRBAR + RASRRBAR + RLAR; attributes through MAIR
Region sizePower of two, naturally alignedBase/limit with 32-byte granularity
SubregionsEight for eligible regionsNot the Armv8-M region model
Read/write accessIncludes explicit no access (AP=000)AP encodes read-only/read-write and privilege; no equivalent explicit no-access AP
Protection of a holeOverlay a no-access regionDeliberately leave a gap unmapped while disabling or constraining privileged default-map access, or use read-only for write protection
MPU availabilityOptional on some coresImplementation-dependent; consult the MCU data sheet

On Armv8-M, a read-only region is useful against writes, but it does not prohibit reads. A truly inaccessible gap requires careful full memory-region planning, especially when MPU_CTRL.PRIVDEFENA permits privileged access to addresses outside defined regions. Check the specific Security state (Secure/Non-secure) and any RTOS MPU scheme.

ARMv7-M Guard Region Implementation (Cortex-M3/M4/M7)

For Armv7-M, reserve a separate, unused, 32-byte aligned guard area immediately below the low-address end of a stack. Do not point the guard at the first usable bytes of the stack: doing so would fault on valid stack accesses. The linker must reserve this area explicitly; do not overlay .bss, the vector table or unrelated objects.

This CMSIS-based example configures one no-access 32-byte Armv7-M region. It assumes the firmware owns the MPU and that the privileged background map is an intentional part of its protection model. An RTOS-managed MPU must instead be configured through its own port hooks.

#include <stdbool.h>
#include <stdint.h>
#include "core_cm4.h" /* Select your processor-specific CMSIS header. */
bool mpu_v7m_install_stack_guard(uint32_t region, uintptr_t guard_addr)
{
uint32_t regions = (MPU->TYPE >> MPU_TYPE_DREGION_Pos) & 0xffu;
if (regions == 0u || region >= regions ||
(guard_addr & 31u) != 0u) {
return false;
}
/* Call during early boot, before other code owns the MPU. */
MPU->CTRL = 0u;
__DSB();
__ISB();
MPU->RNR = region;
MPU->RBAR = (uint32_t)guard_addr;
/* XN, AP=000 (no access), 32-byte region, enabled. */
MPU->RASR = (1u << 28) | (4u << 1) | 1u;
SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk;
/* Enable MPU; privileged background region allowed by design. */
MPU->CTRL = MPU_CTRL_ENABLE_Msk | MPU_CTRL_PRIVDEFENA_Msk;
__DSB();
__ISB();
return true;
}

The caller must check the actual reserved guard address, e.g., a linker-exported _stack_guard_start, not derive it by rounding an arbitrary pointer down. This example overwrites MPU configuration state if used after another MPU owner; merge with existing regions instead of calling it unchanged in production.

Also, guarding only the main stack will not guard RTOS thread stacks using PSP. If per-task guards share a region index, the scheduler must update it safely on context switches.

ARMv8-M Guard Region Implementation (Cortex-M33/M55)

Armv8-M Mainline has a different MPU programming model. The following CMSIS example sets a 32-byte write-protected (read-only) guard. This blocks CPU writes from either privilege level but still permits reads; it is not a universal no-access trap. This is intentionally different from the Armv7-M example.

#include <stdbool.h>
#include <stdint.h>
#include "core_cm33.h" /* Select the target's CMSIS Armv8-M header. */
bool mpu_v8m_install_ro_guard(uint32_t region, uint32_t base)
{
uint32_t regions = (MPU->TYPE >> MPU_TYPE_DREGION_Pos) & 0xffu;
if (regions == 0u || region >= regions || (base & 31u) != 0u) {
return false;
}
/* Early-boot example only; preserve any MPU/RTOS-owned regions. */
ARM_MPU_Disable();
ARM_MPU_SetMemAttr(0u, ARM_MPU_ATTR(ARM_MPU_ATTR_NON_CACHEABLE,
ARM_MPU_ATTR_NON_CACHEABLE));
ARM_MPU_SetRegion(region,
ARM_MPU_RBAR(base, ARM_MPU_SH_NON,
ARM_MPU_AP_RO, ARM_MPU_AP_NP, ARM_MPU_XN),
ARM_MPU_RLAR(base + 31u, 0u));
SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk;
ARM_MPU_Enable(MPU_CTRL_PRIVDEFENA_Msk);
return true;
}

The byte range [base, base + 31] must be genuinely reserved in the linker layout and must not contain valid data. A full no-access gap on Armv8-M needs a whole-memory mapping design that does not let privileged background mapping grant access to the gap. If hardware stack-limit registers (MSPLIM/PSPLIM) are available, they are also useful for downward-growing stack protection. Check the actual core, Security state and firmware framework before selecting a technique.

Decoding the MemManage Fault

For Cortex-M cores implementing the configurable fault registers, SCB->CFSR contains the MemManage status bits in its low byte. MMARVALID indicates when MMFAR contains an address relevant to the reported fault. Do not dereference a stacked frame blindly: MSTKERR, MUNSTKERR or an exhausted MSP may mean the frame itself is incomplete or invalid.

#include <stdint.h>
#include "core_cm4.h" /* Select the actual CMSIS core header. */
typedef struct {
uint32_t cfsr;
uint32_t mmfar;
uint32_t frame_may_be_invalid;
} memfault_snapshot_t;
memfault_snapshot_t read_memfault_snapshot(void)
{
uint32_t cfsr = SCB->CFSR;
uint32_t mmfsr = cfsr & 0xffu;
memfault_snapshot_t s = {
.cfsr = cfsr,
.mmfar = (mmfsr & (1u << 7)) ? SCB->MMFAR : 0u,
.frame_may_be_invalid =
(mmfsr & ((1u << 3) | (1u << 4) | (1u << 5))) != 0u
};
return s;
}

IACCVIOL and DACCVIOL describe instruction or data permission failures; MSTKERR/MUNSTKERR indicate stacking/unstacking errors. Read SCB->HFSR too if the fault escalated. Record telemetry using a reserved fault stack or a small fault handler that does not depend on the damaged application stack.

+----------------------------------------------------------------------+
| MEMMANAGE FAULT DIAGNOSTICS |
+----------------------------------------------------------------------+
| |
| CFSR low byte (MMFSR) |
| bit 0: IACCVIOL Instruction access violation |
| bit 1: DACCVIOL Data access violation |
| bit 3: MUNSTKERR Unstacking problem |
| bit 4: MSTKERR Stacking problem |
| bit 5: MLSPERR Lazy FP state preservation problem |
| bit 7: MMARVALID MMFAR address is valid |
| |
| Fault frame may not be usable after stacking errors. |
+----------------------------------------------------------------------+

Compiler Hardening: Catch Bugs at Compile Time

Warnings, static analysis and compiler-inserted checks complement runtime guards. Unlike an MPU, most compiler diagnostics do not prevent a write at runtime. Start with warnings and audited dependencies; enable instrumentation on test builds and measure the actual code-size/latency impact on the target.

# Makefile example: choose flags supported by the selected GCC/Clang.
CFLAGS += -Wall -Wextra -Wpedantic \
-Werror=implicit-function-declaration \
-Werror=incompatible-pointer-types \
-Werror=int-conversion \
-Wshadow -Wconversion -Warray-bounds \
-Wstringop-overflow
# Selectively enable after verifying target runtime support:
CFLAGS += -fstack-protector-strong
# On suitable toolchain versions, test uninitialized locals with:
# CFLAGS += -ftrivial-auto-var-init=pattern

_FORTIFY_SOURCE is libc/header dependent and frequently offers little or no benefit on newlib-nano bare-metal builds. -fno-common is already the GCC default in modern releases. -fstrict-aliasing at optimization levels is not a memory-safety tool: write correct aliasing code instead. None of these settings replaces bounds checking and lifetime management.

Compiler Hardening Flag Matrix

OptionWhat it doesLimitations
-Wall -WextraBroad compile-time warningsDoes not prove memory safety
-WconversionHighlights narrowing/signedness conversionsMay need targeted suppression after review
-Warray-boundsFlags some provable out-of-bounds accessesDepends on optimization and available sizes
-fstack-protector-strongChecks selected function-frame guardsDetects only some overwrites, usually on return
-D_FORTIFY_SOURCE=2Adds object-size checks in supported libc headersRequires compatible libc and optimization; not universal on bare metal
-ftrivial-auto-var-init=patternInitializes some automatic storage to a markerNot a substitute for correct initialization; incurs cost
-fsanitize=address,undefinedFinds many errors in host testsShadow memory, runtime and platform support needed

Avoid universal percentage-overhead claims: measure each technique using your compiler, optimization flags, MCU and workload.

Complete Debugging Workflow

Proceed from evidence to instrumentation; do not assume every unexplained crash comes from memory corruption.

+----------------------------------------------------------------------+
| CORRUPTION DEBUG WORKFLOW |
+----------------------------------------------------------------------+
| |
| [1] Capture CFSR/HFSR, MSP/PSP and usable exception frame |
| | |
| v |
| [2] Determine if fault is precise and whether stack is valid |
| | |
| v |
| [3] Check allocated object bounds, stack marks, allocator state |
| | |
| v |
| [4] Identify a known corrupted address (if one exists) |
| | |
| v |
| [5] Set GDB hardware write watchpoint on that address |
| | |
| v |
| [6] Reproduce the fault and inspect PC + disassembly |
| | |
| v |
| [7] Fix root cause; validate under stress and target hardware |
| | |
| v |
| [8] Add permanent bounds checks, instrumentation or MPU protection |
| |
| If DMA is the writer, use DMA-specific tracing or protection. |
+----------------------------------------------------------------------+

A broken canary suggests that region was overwritten but does not by itself identify the cause. A high-water mark of zero indicates exhausted recorded slack; a positive mark does not guarantee that no overflow or stray write occurred.

HardFault Trampoline: Preserving the True Fault Context

On Armv7-M Cortex-M3/M4/M7, EXC_RETURN bit 2 identifies whether exception entry used MSP or PSP. If the FPU saved an extended exception frame, the basic R0-R3/R12/LR/PC/xPSR frame is offset within it. A stacking fault may leave no valid frame to decode; check CFSR before touching it.

The following example is for Armv7-M Thumb-2 cores. It is not a drop-in handler for Cortex-M0/M0+, TrustZone transitions or every FPU/RTOS configuration. The handler itself still requires a valid MSP; for serious stack-corruption diagnostics, arrange a dedicated fault stack at startup.

#include <stdint.h>
#define CFSR_REG (*(volatile const uint32_t *)0xE000ED28u)
#define HFSR_REG (*(volatile const uint32_t *)0xE000ED2Cu)
volatile uint32_t fault_snapshot_cfsr;
volatile uint32_t fault_snapshot_hfsr;
volatile uint32_t fault_snapshot_pc;
volatile uint32_t fault_snapshot_lr;
volatile uint32_t fault_snapshot_exc_return;
__attribute__((noreturn))
void HardFault_Handler_C(const uint32_t *saved_sp, uint32_t exc_return);
__attribute__((naked)) void HardFault_Handler(void)
{
__asm volatile (
"tst lr, #4\n"
"ite eq\n"
"mrseq r0, msp\n"
"mrsne r0, psp\n"
"mov r1, lr\n"
"b HardFault_Handler_C\n"
);
}
__attribute__((noreturn))
void HardFault_Handler_C(const uint32_t *saved_sp, uint32_t exc_return)
{
uint32_t cfsr = CFSR_REG;
fault_snapshot_cfsr = cfsr;
fault_snapshot_hfsr = HFSR_REG;
fault_snapshot_exc_return = exc_return;
/* Stacking error flags: MemManage bit 4 and BusFault bit 12. */
if ((cfsr & ((1u << 4) | (1u << 12))) == 0u) {
/* EXC_RETURN bit 4 is 0 for an extended FP exception frame. */
const uint32_t *basic = saved_sp;
if ((exc_return & (1u << 4)) == 0u) {
basic += 18; /* S0-S15, FPSCR, reserved word. */
}
fault_snapshot_lr = basic[5];
fault_snapshot_pc = basic[6];
}
for (;;) {
__asm volatile ("nop"); /* Inspect snapshots with a debugger. */
}
}

The handler deliberately does not printf, access an invalid MMFAR/BFAR, or execute BKPT unconditionally when no debugger is attached. Review the generated assembly and exception frame format for your target, including lazy FP stacking and the RTOS’s exception wrapper.

Real-World Example: UART RX Overrun Corrupting Adjacent State

A UART receive routine that increments a buffer index without a bounds check can eventually write beyond its allocated array. Demonstrating which neighboring object is modified requires known storage layout; ordinary unrelated static declarations are not guaranteed to be adjacent or ordered in RAM.

Here is a deliberately packed containing object for a reproducible diagnostic demonstration. Do not rely on this layout as a safe packet storage design.

The Bug

#include <stdint.h>
#include <stddef.h>
#define UART_RX_BUF_SIZE 128u
typedef struct {
uint32_t magic_key;
uint32_t baud_rate;
uint8_t node_id;
} device_config_t;
typedef struct {
uint8_t rx[UART_RX_BUF_SIZE];
device_config_t config;
} uart_state_t;
static uart_state_t uart_state = {
.config = { .magic_key = UINT32_C(0xABCD1234),
.baud_rate = 115200u, .node_id = 1u }
};
static volatile uint16_t rx_count;
void bad_uart_receive_byte(uint8_t byte)
{
/* BUG: access is undefined when rx_count >= UART_RX_BUF_SIZE. */
uart_state.rx[rx_count++] = byte;
}

Because rx is the first field and the following device_config_t begins at a documented struct offset, a compiler may generate a store that damages it. C does not guarantee an observable result for an out-of-bounds access, even when neighboring members are adjacent. The example is for fault reproduction on a controlled test build only.

The Catch via Hardware Watchpoint

Attach a debugger and watch the field that is expected to change. A watchpoint event is evidence of a matching CPU access; the trace is illustrative, not a guaranteed sequence of GDB output or register values.

(gdb) watch -location uart_state.config.magic_key
Hardware watchpoint 1: uart_state.config.magic_key
(gdb) continue
# Example outcome on an affected build:
Hardware watchpoint 1: uart_state.config.magic_key
(gdb) bt
#0 bad_uart_receive_byte (...) at uart.c:...
(gdb) p rx_count
(gdb) x/i $pc

Confirm offsetof(uart_state_t, config) and inspect the disassembly. An optimized compiler may not produce the same memory write after it encounters undefined behaviour; if reproduction is unreliable, also instrument the index and build a checked parser.

The Fix

#include <stdbool.h>
#include <stdint.h>
static volatile bool rx_overrun_detected;
void uart_receive_byte_checked(uint8_t byte)
{
if (rx_count < UART_RX_BUF_SIZE) {
uart_state.rx[rx_count] = byte;
++rx_count;
} else {
rx_overrun_detected = true;
/* Drop the byte; reset the packet parser at a safe boundary. */
}
}

For real STM32 UART ISRs, handle framing/overrun flags according to the exact STM32 family and register version, and reset rx_count as part of the protocol’s packet-framing policy. Use a ring buffer, DMA-safe producer/consumer bounds or protocol length validation when sustained data exceeds a single frame buffer.

Production Deployment Matrix

TechniqueDevelopment useProduction useImportant limitation
DWT watchpointsFind a known CPU writerOnly if debug infrastructure and policy allow itComparator/debug support varies; not a bus-master firewall
Linker sentinelDetect an overwritten boundaryOptional periodic diagnosticDetects after overwrite; can miss overflows
Compiler stack protectorCatch selected frame corruptionOften useful if runtime support is presentFunction coverage and overhead vary
RTOS stack watermarkEstimate stack consumptionUseful as monitored health metricPrior-use estimate, not guaranteed free space
MPU guardFault on forbidden CPU accessesValuable on correctly mapped stacks/buffersCorrect placement, privilege policy, fault stack required
Host AddressSanitizerIdentify memory bugs earlyGenerally host-side for small bare-metal MCUsInstrumentation/runtime/shadow RAM overhead

All hardware and compiler techniques should be validated on the exact MCU, MPU configuration and application load. There is no universal zero-cost, zero-false-negative memory-corruption detector.

Summary

The most productive memory-corruption investigation starts by identifying what data changed, then finding which access changed it. Cortex-M DWT watchpoints are effective for tracing CPU writes to known addresses; they do not prevent the bad write. Canary words and RTOS stack patterns provide useful delayed evidence; they do not protect adjacent memory. MPU guards can block access to deliberately protected regions, subject to architectural permissions, valid stack arrangements and bus-master limitations.

  1. Use fault registers and a verified exception frame to understand the immediate crash.
  2. Use a hardware write watchpoint on a known, valid object address and inspect disassembly at the event.
  3. Enable stack checks and compiler stack protectors as complementary tests, not proof of complete safety.
  4. Reserve MPU guard memory in the linker script and use the correct Armv7-M or Armv8-M permission model.
  5. Validate the fix under production-like interrupt, DMA and compiler-optimization conditions.

The goal is repeatable, evidence-based diagnosis plus a permanent bounds/ownership fix. No guard or watchpoint substitutes for correct object sizes and memory lifetimes.

References

  1. ARM Limited, ARMv7-M Architecture Reference Manual, Section B3.5 “Memory Protection Unit” & Section C1.8 “Data Watchpoint and Trace”, Doc DDI0403E. Available: https://developer.arm.com/documentation/ddi0403/latest
  2. ARM Limited, ARMv8-M Architecture Reference Manual, Section B8 “Protected Memory System Architecture (PMSA)”, Doc DDI0553. Available: https://developer.arm.com/documentation/ddi0553/latest
  3. ARM Limited, Cortex-M4 Devices Generic User Guide, Chapter 4 “Memory Protection Unit”, Doc DUI0553. Available: https://developer.arm.com/documentation/dui0553/latest
  4. FreeRTOS Kernel Documentation, Stack Overflow Checking & uxTaskGetStackHighWaterMark. Available: https://www.freertos.org/Documentation/02-Kernel/02-Kernel-features/01-Tasks-and-co-routines/04-Stack-overflow-checking
  5. FreeRTOS Kernel Documentation, uxTaskGetStackHighWaterMark API Reference. Available: https://www.freertos.org/Documentation/02-Kernel/04-API-references/03-Task-utilities/04-uxTaskGetStackHighWaterMark
  6. GCC Documentation, Instrumentation Options (-fstack-protector, -fstack-clash-protection). Available: https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html
  7. LLVM/Clang Documentation, AddressSanitizer and Hardening Flags. Available: https://clang.llvm.org/docs/AddressSanitizer.html
  8. STMicroelectronics, STM32F4xx Reference Manual (RM0090), Section 4 “Memory Protection Unit (MPU)“. Available: https://www.st.com/resource/en/reference_manual/rm0090-stm32f405415-stm32f407417-stm32f427437-and-stm32f429439-advanced-armbased-32bit-mcus-stmicroelectronics.pdf

Frequently Asked Questions

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

For a known corrupted object, a hardware write watchpoint is often the quickest way to identify the CPU access responsible. In GDB, use a valid object expression such as `watch -location state.magic` and confirm hardware watchpoint support. The event is not a pre-write guard and DMA writes may not be observed by the CPU DWT.

How do stack canaries detect stack overflow before a crash?

A stack-boundary canary is a sentinel placed at the low-address end of a reserved downward-growing stack. Checking its value reveals some past overwrites, but detection happens after the offending write and a large overrun can miss the sentinel. Use an MPU or architectural stack limit for active protection.

When should I use MPU guard regions instead of watchpoints?

Choose a debugger watchpoint to locate a CPU writer during reproduction. Choose a carefully reserved and configured MPU guard to fault on forbidden accesses in deployed firmware. Armv7-M supports an explicit no-access MPU region; Armv8-M uses different permissions and a read-only region prevents writes but not reads.

Can AddressSanitizer catch memory corruption on target hardware?

AddressSanitizer detects many memory errors when application components can be built with a compatible instrumentation runtime and shadow memory, commonly in host unit tests. Most small bare-metal MCU builds cannot readily support its overhead. On target, combine bounds checks, compiler protections, MPU guards, and stack monitoring.

Why does my firmware crash randomly with no clear pattern?

Intermittent crashes can result from corrupt pointers, buffer overruns, DMA mistakes, stack exhaustion, hardware faults, or concurrency bugs. Collect CFSR/HFSR and a valid fault frame, identify what state changed, then set a hardware write watchpoint on the actual object if the CPU is the suspected writer.

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