HomeAbout UsContact Us

Fixing Function Pointer Corruption from Buffer Overruns in C

By Jithin Tom
Published in Embedded C/C++
November 27, 2026
5 min read
Fixing Function Pointer Corruption from Buffer Overruns in C

Table Of Contents

01
The Problem: State Machine Jumps to Nowhere
02
Root Cause: Adjacent Memory Layout
03
Solution 1: Catch Corruption with DWT Watchpoints
04
Solution 2: Bulletproof Circular Buffer
05
Solution 3: Hardening the State Machine
06
ASCII Diagram: Corruption Flow
07
Verification Steps
08
Summary
09
Related Reading
10
References
11
Frequently Asked Questions

Function pointer state machines are a staple of embedded C firmware because they are clean, efficient, and deterministic. But when a nearby ring buffer overruns, it can silently overwrite a function pointer, sending the CPU into a hard fault at an address that makes no sense. The crash site is rarely the bug site. This article shows how to catch the corruption in the act using Cortex-M Data Watchpoint and Trace (DWT), implement bulletproof circular buffers, and harden your state machines against this class of failure.

The Problem: State Machine Jumps to Nowhere

You are debugging a UART driver with a DMA-backed ring buffer. The state machine uses a function pointer table to dispatch events:

typedef void (*state_fn_t)(void);
state_fn_t state_table[] = {
state_idle,
state_rx_header,
state_rx_payload,
state_process,
state_error
};
volatile state_fn_t current_state = state_idle;

The ring buffer sits in RAM right next to current_state. Under load, the DMA writes past the buffer end. One byte overwrites the LSB of current_state. The next state transition jumps to 0x0800xxxx instead of 0x0800yyyy — a valid flash address, but the wrong function. The CPU executes garbage, eventually hitting an UNDEFINSTR or INVSTATE usage fault.

The hard fault handler shows:

CFSR = 0x00008200 (INVSTATE | IBUSERR)
PC = 0x08001234 (middle of a function, not an entry point)
LR = 0xFFFFFFF9 (EXC_RETURN, Thread mode, MSP)

The PC does not point to any function in your map file. Standard backtraces are useless because the stack was never properly set up for the bogus function. The crash appears to be in valid code, but the execution path makes no sense.

Why This Is Hard to Debug

Traditional debugging approaches fail here. Printf debugging changes timing and may mask the overrun. JTAG breakpoints on the state machine functions never hit because the corruption happens in the buffer write routine, not in the state functions themselves. The fault manifests later, when the corrupted function pointer is dereferenced. By then, the stack frame of the corrupting instruction is long gone.

This is why hardware watchpoints are essential. They catch the write at the moment it happens, not millions of cycles later when the symptom appears.

Root Cause: Adjacent Memory Layout

The linker places variables in declaration order unless you force otherwise. A typical map file excerpt:

.bss.current_state 0x20001000 0x4 (function pointer)
.bss.rx_ring_buffer 0x20001004 0x100 (256-byte ring buffer)

Wait — the function pointer comes before the buffer. An overrun past the buffer end would hit whatever follows, not current_state. But if the buffer is declared first:

.bss.rx_ring_buffer 0x20001000 0x100
.bss.current_state 0x20001004 0x4 -- OVERLAP!

Or the buffer write index wraps incorrectly, writing before the buffer start (negative index). Either way, adjacency is the enemy.

The real-world trigger is often a classic off-by-one in the ring buffer:

// BUG: writes to buffer[SIZE] on the last iteration
void ring_push(uint8_t byte) {
buffer[head] = byte;
head = (head + 1) % SIZE; // modulo is slow, but correct
if (head == tail) { /* overflow */ }
}
// BUG: modulo with signed int, negative head wraps to huge positive
head = (head + 1) % SIZE; // if head == -1, result is -1 % 256 = -1 (C99) or 255 (C++?)

On Cortex-M with 16-bit int, uint16_t head promoted to int (16-bit) causes modulo to misbehave when head >= 32768.

Integer Promotion Pitfalls

The C integer promotion rules silently convert uint16_t to int (signed 16-bit on many Cortex-M toolchains) before the modulo operation. When head reaches 32768, the promoted value becomes negative. The modulo of a negative number in C99 yields a negative result, which when converted back to unsigned produces a huge index — far beyond the buffer bounds. This single promotion bug can corrupt kilobytes of RAM before the modulo wraps back.

Solution 1: Catch Corruption with DWT Watchpoints

Cortex-M3/M4/M7 have hardware Data Watchpoint and Trace (DWT) units — up to 4 comparators. You can set a watchpoint on current_state that triggers DebugMon_Handler the moment any instruction writes to it.

DWT Setup Code

#include <stdint.h>
#include "stm32f4xx.h" // or your MCU header
// Enable DWT watchpoint on a variable address
// comparator: 0-3 (DWT_COMP0..3)
// mask: 0 = exact address, 1 = 2-byte, 2 = 4-byte, ... up to 31 = 2GB region
void dwt_watchpoint_enable(uint32_t comparator, void *addr, uint32_t mask_bits) {
// Enable TRC in DEMCR
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
// Unlock DWT (if locked)
DWT->LAR = 0xC5ACCE55;
// Configure comparator
DWT->COMP[comparator] = (uint32_t)addr;
DWT->MASK[comparator] = mask_bits; // 0 = exact 4-byte match
DWT->FUNCTION[comparator] =
(DWT_FUNCTION_DATA_MATCH_Msk | // match on data address
DWT_FUNCTION_DATAVADDR0_Msk | // use COMP0 as address (adjust for comparator)
DWT_FUNCTION_DATAVSIZE_Msk | // match 4-byte access
DWT_FUNCTION_DATAVADDR0_Msk); // enable comparator
// Enable Debug Monitor exception (priority 0 = highest)
NVIC_SetPriority(DebugMonitor_IRQn, 0);
NVIC_EnableIRQ(DebugMonitor_IRQn);
}
// Usage: watch the 4-byte function pointer
dwt_watchpoint_enable(0, &current_state, 0);

Debug Monitor Handler

__attribute__((naked)) void DebugMon_Handler(void) {
__asm volatile (
"MRS R0, PSP\n"
"MRS R1, MSP\n"
"TST LR, #4\n"
"ITE EQ\n"
"MOVEQ R0, R0\n"
"MOVNE R0, R1\n"
"B dwt_debugmon_c\n"
);
}
void dwt_debugmon_c(uint32_t *sp) {
// sp[6] = PC, sp[5] = LR, sp[4] = R12, sp[3] = R3, sp[2] = R2, sp[1] = R1, sp[0] = R0
uint32_t fault_pc = sp[6];
uint32_t fault_lr = sp[5];
// Log the corrupting instruction address
log_corruption(fault_pc, fault_lr, (void *)&current_state);
// Optional: break into debugger
__asm volatile ("BKPT #0");
// Clear DWT match flag
DWT->FUNCTION[0] &= ~DWT_FUNCTION_MATCHED_Msk;
}

Now when the ring buffer overrun writes to current_state, you get the exact instruction that did it — the STR instruction in your buffer push routine. No guessing.

Verifying DWT Works

// Test: deliberately corrupt the pointer
void test_dwt(void) {
dwt_watchpoint_enable(0, &current_state, 0);
current_state = state_idle; // This should NOT trigger (same value)
current_state = state_error; // This SHOULD trigger watchpoint
}

If DebugMon_Handler fires on the second write, DWT is working. If not, check:

  • CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA_Msk is set
  • DWT->LAR unlock succeeded (read back should be 1)
  • DWT->FUNCTION[0] & DWT_FUNCTION_MATCHED_Msk sets after write
  • DebugMonitor_IRQn is enabled in NVIC

Understanding DWT Comparator Configuration

Each DWT comparator can match on instruction address (PC), data address, or data value. For catching buffer overruns, we need data address matching. The FUNCTION register controls the match type:

  • Bit 0 (EMITRANGE): Emit range field
  • Bit 12-15 (DATAVADDR): Which comparator holds the address (0-3)
  • Bit 16-19 (DATAVSIZE): Size of data access (0=byte, 1=halfword, 2=word)
  • Bit 20-23 (DATAVMATCH): Match on data value (not used here)
  • Bit 24 (CYCMATCH): Cycle counter match
  • Bit 25 (EMITRANGE): Emit range field
  • Bit 26-27 (FUNCTION): 0=disabled, 1=instruction address, 2=data address read, 3=data address write, 4=data address read/write

For our use case, FUNCTION=3 (data address read/write) with DATAVSIZE=2 (word access) and DATAVADDR pointing to the comparator holding the address.

Solution 2: Bulletproof Circular Buffer

The root cause is the buffer implementation. Here is a pattern that eliminates the off-by-one class of bugs entirely.

Power-of-Two Size with Bitmask

#define RING_SIZE 256 // Must be power of 2
#define RING_MASK (RING_SIZE - 1)
typedef struct {
uint8_t data[RING_SIZE];
volatile uint16_t head; // Written by producer (ISR/DMA)
volatile uint16_t tail; // Read by consumer (main loop)
volatile uint16_t count; // Atomic shared state
} ring_buffer_t;
ring_buffer_t rx_ring;
// Producer (ISR or DMA callback) - only modifies head, count
void ring_push_isr(ring_buffer_t *rb, uint8_t byte) {
uint16_t next_head = (rb->head + 1) & RING_MASK;
if (next_head == rb->tail) {
// Buffer full -- handle overflow
rb->overflow_count++;
return;
}
rb->data[rb->head] = byte;
__asm volatile ("" ::: "memory"); // Compiler barrier
rb->head = next_head;
__asm volatile ("" ::: "memory");
rb->count++; // Updated LAST -- consumer sees new count only after data is visible
}
// Consumer (main loop) - only modifies tail, count
bool ring_pop(ring_buffer_t *rb, uint8_t *byte) {
if (rb->count == 0) {
return false;
}
*byte = rb->data[rb->tail];
__asm volatile ("" ::: "memory");
rb->tail = (rb->tail + 1) & RING_MASK;
__asm volatile ("" ::: "memory");
rb->count--; // Updated LAST -- producer sees space only after tail moved
return true;
}

Why This Works

PropertyMechanism
No modulo& (SIZE-1) is single-cycle on Cortex-M
No signed overflowuint16_t wraps defined by C standard
Atomic countSingle 16-bit read/write is atomic on Cortex-M
Memory orderingCompiler barriers prevent reordering around volatile
Full/empty unambiguouscount == 0 empty, count == SIZE full (but we never let it reach SIZE)

Critical: count is the only shared variable used for synchronization decisions. Head and tail are updated after data movement, and count is updated last. This makes the buffer lock-free for single-producer/single-consumer.

Why Modulo Is the Enemy

The modulo operator % is not a single instruction on Cortex-M0/M0+/M3/M4. It expands to a library call (__aeabi_uidivmod or similar) taking 10-20 cycles. Worse, it introduces signed/unsigned promotion bugs as shown earlier. The bitmask & (SIZE-1) compiles to a single AND instruction — zero cycles on most pipelines since it pairs with the load/store.

DMA Integration

For DMA, the producer is hardware. Configure DMA in circular mode with RING_SIZE buffer. The DMA “head” is RING_SIZE - DMA_Stream->NDTR. Consumer reads up to that position:

void ring_dma_consumer(ring_buffer_t *rb) {
uint16_t dma_head = RING_SIZE - DMA1_Stream5->NDTR;
uint16_t available = (dma_head - rb->tail) & RING_MASK;
for (uint16_t i = 0; i < available; i++) {
uint8_t byte = rb->data[rb->tail];
rb->tail = (rb->tail + 1) & RING_MASK;
process_byte(byte);
}
rb->count = available; // Sync count with reality
}

This approach works because DMA writes are naturally sequential and the NDTR register gives the exact write position. No interrupt latency, no ISR overhead.

Solution 3: Hardening the State Machine

Even with a correct buffer, defense-in-depth adds safety against unexpected corruption sources (cosmic rays, DMA bugs, stack overflow from unrelated code).

1. Validate Function Pointer Before Call

// Known valid range: flash (0x08000000 - 0x080FFFFF for 1MB flash)
#define FLASH_START 0x08000000
#define FLASH_END 0x08100000
bool is_valid_state_fn(state_fn_t fn) {
uintptr_t addr = (uintptr_t)fn;
return (addr >= FLASH_START && addr < FLASH_END && (addr & 1) == 1); // Thumb bit set
}
void state_machine_run(void) {
if (!is_valid_state_fn(current_state)) {
// Corruption detected -- safe recovery
log_error("Invalid state fn: %p", (void*)current_state);
current_state = state_error;
return;
}
current_state(); // Safe to call
}

The Thumb bit (LSB=1) check is crucial — Cortex-M requires it for all function entries. A corrupted pointer with LSB=0 would cause INVSTATE usage fault on branch.

2. Place Guard Region Around Critical Variables

// In linker script or via section attribute
__attribute__((section(".critical_data")))
volatile struct {
uint32_t canary1;
state_fn_t current_state;
uint32_t canary2;
} sm_state = {
.canary1 = 0xDEADBEEF,
.current_state = state_idle,
.canary2 = 0xFEEDFACE
};
// Periodic check (e.g., in SysTick or watchdog task)
void check_state_machine_integrity(void) {
if (sm_state.canary1 != 0xDEADBEEF || sm_state.canary2 != 0xFEEDFACE) {
trigger_safe_shutdown("State machine canary corrupted");
}
}

Canaries detect any overwrite of the critical region, not just function pointer corruption. The 32-bit patterns 0xDEADBEEF and 0xFEEDFACE are chosen because they are unlikely to appear naturally in RAM.

3. Use MPU to Protect Critical Region

On Cortex-M4/M7 with MPU, make the state variable read-only in normal operation:

// MPU Region 0: Flash (execute, read)
// MPU Region 1: RAM (read/write)
// MPU Region 2: State machine variables (read-only)
void mpu_protect_state_machine(void) {
// Region base = &sm_state, size = 32 bytes (round up to 32B)
MPU->RBAR = ((uint32_t)&sm_state) & ~0x1F;
MPU->RASR = (0x2 << MPU_RASR_AP_Pos) | // RO for privileged, no user access
(0x4 << MPU_RASR_SIZE_Pos) | // 32 bytes
MPU_RASR_ENABLE_Msk;
MPU->CTRL |= MPU_CTRL_ENABLE_Msk;
// To update state, temporarily disable MPU or use privileged handler
}

Note: This requires the state machine to run in privileged mode, or updates via SVC call. The MPU region size must be a power of two, minimum 32 bytes, aligned to its size.

ASCII Diagram: Corruption Flow

+------------------------------------------------------------------+
| MEMORY LAYOUT (TYPICAL) |
+------------------------------------------------------------------+
| 0x20001000 | rx_ring_buffer[0..255] | 256 bytes |
| 0x20001100 | current_state (fn ptr) | 4 bytes |
| 0x20001104 | tx_ring_buffer[0..255] | 256 bytes |
+------------------------------------------------------------------+
| BUG: DMA WRITES PAST rx_ring_buffer END |
| rx_ring_buffer[256] --> OVERWRITES current_state LSB |
+------------------------------------------------------------------+
| STATE TRANSITION: |
| current_state() --> JUMPS TO 0x0800xxxx |
| (valid flash, wrong function) |
+------------------------------------------------------------------+
| HARD FAULT: CFSR.INVSTATE = 1 |
| PC = 0x08001234 (middle of function) |
+------------------------------------------------------------------+
| DWT WATCHPOINT TRIGGERS: |
| DebugMon_Handler catches STR at fault_pc |
+------------------------------------------------------------------+

Verification Steps

1. Unit Test the Ring Buffer

void test_ring_buffer(void) {
ring_buffer_t rb = {0};
uint8_t data[] = {0x01, 0x02, 0x03, 0x04};
// Fill to capacity-1
for (int i = 0; i < RING_SIZE - 1; i++) {
ring_push_isr(&rb, i);
}
assert(rb.count == RING_SIZE - 1);
// Next push should detect full
ring_push_isr(&rb, 0xFF);
assert(rb.overflow_count == 1);
assert(rb.count == RING_SIZE - 1); // Unchanged
// Pop all
for (int i = 0; i < RING_SIZE - 1; i++) {
uint8_t val;
assert(ring_pop(&rb, &val));
assert(val == i);
}
assert(rb.count == 0);
assert(!ring_pop(&rb, &val)); // Empty
// Wrap-around test
for (int cycle = 0; cycle < 3; cycle++) {
for (int i = 0; i < 100; i++) ring_push_isr(&rb, i);
for (int i = 0; i < 100; i++) {
uint8_t val; ring_pop(&rb, &val); assert(val == i);
}
}
}

2. Inject Buffer Overrun in CI

// Test harness: deliberately overrun and verify DWT catches it
void test_dwt_catches_overrun(void) {
dwt_watchpoint_enable(0, &sm_state.current_state, 0);
// Simulate buggy buffer that writes past end
uint8_t *buf = rx_ring.data;
for (int i = 0; i < RING_SIZE + 8; i++) {
buf[i] = 0xAA; // Overruns into current_state at i=256
}
// DWT should have triggered
assert(dwt_was_triggered(0));
uint32_t fault_pc = dwt_get_fault_pc();
// fault_pc should point to the STR instruction in this loop
}

3. Static Analysis

Run Clang Static Analyzer and MISRA checker:

## Clang tidy checks for buffer overruns
clang-tidy -checks='-*,bugprone-*,clang-analyzer-*' \
ring_buffer.c -- -std=c11 -DSTM32F4
## MISRA C:2012 Rule 18.1 (pointer arithmetic bounds)
cppcheck --enable=all --std=c11 --addon=misra.py ring_buffer.c

Summary

Function pointer corruption from buffer overruns is a silent killer in embedded C. The crash appears in a valid flash address, far from the bug site. Three defenses work together:

  1. DWT watchpoints catch the corruption at the moment it happens — the single most effective debugging tool for this class of bug.
  2. Power-of-two ring buffers with atomic count eliminate the off-by-one and signed-wrap root causes.
  3. State machine hardening (canaries, pointer validation, MPU) ensures that even if corruption occurs, the system fails safely.

The DWT technique applies beyond state machines — any global variable that “mysteriously changes” can be watched. On Cortex-M33/MCU with TrustZone, the same DWT unit works in both secure and non-secure worlds.

Next time your state machine jumps to 0x0800xxxx and the backtrace shows garbage, do not stare at the fault handler. Set a watchpoint on the function pointer and let the hardware tell you who wrote to it.

References

  1. ARM Limited. Cortex-M4 Devices Generic User Guide: Debug Watchpoint and Trace (DWT). ARM DUI 0553A. https://interrupt.memfault.com/blog/cortex-m-watchpoints
  2. ARM Limited. Cortex-M4 Technical Reference Manual: Memory Protection Unit (MPU). ARM DDI 0439D. https://support.arm.com/documentation/ddi0439/d
  3. Joseph Yiu. The Definitive Guide to ARM Cortex-M3 and Cortex-M4 Processors, 3rd ed. Newnes, 2014. Chapter 12 (Debug), Chapter 14 (MPU).
  4. STMicroelectronics. STM32F4 Series Reference Manual: Debug Support (DBGMCU), DWT, and MPU. RM0090 Rev 20. 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
  5. FreeRTOS. Stack Usage and Stack Overflow Checking. https://freertos.org/Documentation/02-Kernel/02-Kernel-features/09-Memory-management/02-Stack-usage-and-stack-overflow-checking
  6. MISRA C:2012. Rule 18.1: Pointer arithmetic shall not be applied to pointers that address a non-array object. MIRA Limited.
  7. CERT C Coding Standard. ARR30-C: Do not form or use out-of-bounds pointers or array subscripts. https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/arrays-arr/arr30-c/
  8. Chris Coleman. Faster Debugging with Watchpoints. Interrupt / Memfault, 2020. https://interrupt.memfault.com/blog/cortex-m-watchpoints

Frequently Asked Questions

Why do buffer overruns corrupt function pointers in state machines?

Function pointers stored near ring buffers or circular queues can be overwritten when the buffer write index exceeds its bounds. Since state machines often use function pointer tables for state transitions, a single byte overrun can redirect execution to an invalid address, causing a hard fault.

How do I detect function pointer corruption on Cortex-M?

Set a data watchpoint (DWT) on the function pointer variable. When the buffer overrun writes to that address, the DebugMon_Handler triggers, letting you catch the exact instruction that corrupts the pointer. Enable DWT by setting DEMCR.TRCENA and configuring DWT_COMPn and DWT_MASKn registers.

What is the safest way to implement a circular buffer in C?

Use a single atomic count variable (volatile) updated last in the producer and first in the consumer. Keep head/tail indices as local variables, only committing them after data is written. Size the buffer as a power of two and use bitmask wrapping (index & (size - 1)) instead of modulo for efficiency and correctness.

Can compiler optimizations hide buffer overrun bugs?

Yes. With -O2/-O3, the compiler may reorder writes or eliminate 'dead' stores, making the overrun manifest differently or disappear in release builds. Always test with the same optimization level as production, and use -fno-strict-aliasing if type-punning through unions is involved.

How do I prevent flash corruption from rogue function pointers?

Place a guard region of invalid instructions (e.g., UD2 or BKPT) before flash write routines. Verify a hardware interlock (GPIO pin or register) before any flash operation. Initialize flash address variables to invalid addresses and only set them in a separate, protected API call.

Tags

embedded-cdebuggingstate-machinesbuffer-overflowfunction-pointerscortex-mhard-fault

Share


Previous Article
Fixing Buildroot Kernel Panic: VFS Unable to Mount Root FS
Jithin Tom

Jithin Tom

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

Related Posts

Fixing Embedded C Memory Corruption: Watchpoints, Canaries, and MPU Guards
Fixing Embedded C Memory Corruption: Watchpoints, Canaries, and MPU Guards
November 23, 2026
11 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media