
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.
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.
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.
| Pattern | Typical cause | What to investigate |
|---|---|---|
| Buffer overrun | Incorrect index, unbounded copy | Array size, object layout, parser lengths |
| Use-after-free / double-free | Expired ownership, allocator misuse | Allocation lifetimes and heap metadata |
| Stack exhaustion | Large arrays, recursion, deep interrupt nesting | MSP/PSP limits, per-thread stack usage |
| Integer overflow | Wrapped allocation-size or index calculation | Checked multiplication/addition before allocation |
| Strict-aliasing violation | Access through an incompatible object pointer | Effective types and compiler optimization |
| Unaligned access | Assumed pointer alignment | Architecture, access width and CCR.UNALIGN_TRP |
| DMA overwrite | Incorrect DMA length or cache-coherency handling | Transfer 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.
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.
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.
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.
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.
| Debug target | Better watchpoint target | GDB example |
|---|---|---|
| Buffer overflow | First known adjacent object field | watch -location app_state.config.magic_number |
| Heap corruption | A verified allocator metadata field | watch -location heap_header->size |
| Stack boundary | A dedicated canary object | watch -location stack_canary_word |
| Function-pointer overwrite | Pointer storage | watch -location callback_ptr |
| Global-variable clobber | The object being changed | watch -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-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.
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. */} > RAMASSERT((_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 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. |+----------------------------------------------------------------------+
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’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.confCONFIG_INIT_STACKS=yCONFIG_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.
-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 supportCFLAGS += -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.
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.
| Feature | Armv7-M MPU (M3/M4/M7) | Armv8-M Mainline MPU (M33/M55/M85) |
|---|---|---|
| Region controls | RBAR + RASR | RBAR + RLAR; attributes through MAIR |
| Region size | Power of two, naturally aligned | Base/limit with 32-byte granularity |
| Subregions | Eight for eligible regions | Not the Armv8-M region model |
| Read/write access | Includes explicit no access (AP=000) | AP encodes read-only/read-write and privilege; no equivalent explicit no-access AP |
| Protection of a hole | Overlay a no-access region | Deliberately leave a gap unmapped while disabling or constraining privileged default-map access, or use read-only for write protection |
| MPU availability | Optional on some cores | Implementation-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.
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 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.
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. |+----------------------------------------------------------------------+
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.
| Option | What it does | Limitations |
|---|---|---|
-Wall -Wextra | Broad compile-time warnings | Does not prove memory safety |
-Wconversion | Highlights narrowing/signedness conversions | May need targeted suppression after review |
-Warray-bounds | Flags some provable out-of-bounds accesses | Depends on optimization and available sizes |
-fstack-protector-strong | Checks selected function-frame guards | Detects only some overwrites, usually on return |
-D_FORTIFY_SOURCE=2 | Adds object-size checks in supported libc headers | Requires compatible libc and optimization; not universal on bare metal |
-ftrivial-auto-var-init=pattern | Initializes some automatic storage to a marker | Not a substitute for correct initialization; incurs cost |
-fsanitize=address,undefined | Finds many errors in host tests | Shadow memory, runtime and platform support needed |
Avoid universal percentage-overhead claims: measure each technique using your compiler, optimization flags, MCU and workload.
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.
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.
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.
#include <stdint.h>#include <stddef.h>#define UART_RX_BUF_SIZE 128utypedef 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.
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_keyHardware 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.
#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.
| Technique | Development use | Production use | Important limitation |
|---|---|---|---|
| DWT watchpoints | Find a known CPU writer | Only if debug infrastructure and policy allow it | Comparator/debug support varies; not a bus-master firewall |
| Linker sentinel | Detect an overwritten boundary | Optional periodic diagnostic | Detects after overwrite; can miss overflows |
| Compiler stack protector | Catch selected frame corruption | Often useful if runtime support is present | Function coverage and overhead vary |
| RTOS stack watermark | Estimate stack consumption | Useful as monitored health metric | Prior-use estimate, not guaranteed free space |
| MPU guard | Fault on forbidden CPU accesses | Valuable on correctly mapped stacks/buffers | Correct placement, privilege policy, fault stack required |
| Host AddressSanitizer | Identify memory bugs early | Generally host-side for small bare-metal MCUs | Instrumentation/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.
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.
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.
Quick Links
Legal Stuff





