Embedded C failures often appear unrelated to their cause: a hard fault may begin with a corrupted buffer, an intermittent reset may be a stack overflow, and an interrupt race may only surface under a particular timing window. This checklist gives you a repeatable way to narrow those failures using compiler diagnostics, map files, assertions, watchpoints, fault registers, logging, and scheduled review checkpoints.
Overview
Debugging microcontroller firmware is easier when you treat each crash as evidence rather than as an isolated event. Start by preserving the exact symptom, build configuration, input conditions, and recent code changes. Then separate the investigation into four areas: memory layout, control flow, concurrency, and hardware state.
A useful first rule is to reproduce the failure with the same optimization level and linker configuration used in the affected build. A debug build can make a problem easier to inspect, but it may change timing, register allocation, stack usage, and interrupt behavior. Keep both a diagnostic build and a production-like build available.
The following symptom-to-cause table is a starting point, not a substitute for evidence:
| Symptom | Likely areas | First checks |
|---|---|---|
| Immediate hard fault after a function call | Invalid function pointer, bad return address, unaligned or illegal access | Fault registers, stacked program counter, pointer validity, disassembly |
| Failure after sustained runtime | Stack growth, heap fragmentation, resource leak, counter rollover | High-water marks, allocation history, periodic health logs |
| Data changes unexpectedly | Buffer overwrite, race condition, DMA ownership error | Watchpoints, guard bytes, interrupt and DMA access paths |
| Failure only with interrupts enabled | Non-atomic shared state, reentrancy, priority interaction | Critical sections, volatile usage, ISR call graph, event traces |
| Reset with little diagnostic output | Watchdog, brownout, lockup, fault-handler failure | Reset-cause register, retained fault record, power and clock status |
What to track
Compiler warnings and static findings
Make warnings part of the normal debugging loop. Enable a strong warning set appropriate to your compiler, then treat new warnings as review items rather than allowing them to accumulate. Pay particular attention to implicit conversions, signedness changes, missing prototypes, suspicious comparisons, shadowed variables, uninitialized values, and unreachable code.
Warnings cannot prove that firmware is correct, but they frequently expose the conditions that later become pointer bugs or buffer corruption. Add static analysis where the project can support it, and record which findings are intentionally suppressed and why.
Linker map and memory layout
Review the linker map after major feature changes and before a release. Record flash usage, RAM usage, section placement, interrupt vector location, and the boundaries of the main stack, process stacks, heaps, DMA buffers, and special memory regions. Confirm that the startup code initializes the regions your application expects.
A map file is especially useful when a failure appears after adding a seemingly unrelated global variable. A small change can move a buffer next to a sensitive object, reduce available stack, or expose an incorrect linker assumption. Keep the map file with the exact binary and compiler configuration used for testing.
Stack and heap behavior
Measure stack usage instead of estimating it from source indentation. A common technique is to fill an unused stack region with a known pattern during initialization and inspect how far the pattern has been overwritten after representative workloads. Track the minimum remaining margin during startup, communication bursts, logging, and error handling.
For heap use, record allocation size, caller or subsystem, lifetime, and failure result where practical. In small firmware systems, a fixed-block pool or static allocation may be easier to reason about than general-purpose dynamic allocation. If an RTOS is present, inspect each task's stack high-water mark and configure its stack-overflow hook if the kernel provides one. Do not assume that the idle task's margin represents the worst case for every task.
Pointers, buffers, and ownership
For each pointer passed across a module, interrupt, DMA engine, or task boundary, document its owner, valid lifetime, size, alignment requirements, and whether it may be null. Prefer APIs that carry a buffer length alongside a pointer. Check arithmetic before indexing, especially when lengths are unsigned and subtraction can wrap.
Use guard bytes around high-risk buffers during testing. A changed guard indicates memory corruption even if the firmware has not crashed yet. Hardware watchpoints can then identify the instruction that writes the damaged location. Watchpoints are limited resources on many microcontrollers, so use them for a narrowed reproduction rather than leaving them enabled indiscriminately.
Interrupt and DMA interactions
List every variable shared between an interrupt service routine and foreground code or an RTOS task. Mark whether access is atomic on the target architecture, whether it needs volatile, and whether a critical section or queue is required. volatile tells the compiler that a value may change outside the current flow; it does not make a multi-step operation atomic and does not replace synchronization.
For DMA, track buffer ownership explicitly: CPU-owned, peripheral-owned, or ready for handoff. Confirm cache maintenance requirements on cores with data caches, and verify that a buffer remains valid until the transfer completes. These checks are often more productive than adding delays to mask a timing problem.
Fault context and reset cause
On Cortex-M devices, fault investigation commonly includes the stacked program counter and link register, the configurable fault status registers, the hard-fault status register, and the configurable fault address registers when implemented. Exact register names and availability vary by core and vendor, so use the reference manual for the target MCU rather than copying a handler between families without review.
Capture reset-cause flags early during startup, before later initialization clears or changes them. Store a compact fault record in retained RAM or another suitable diagnostic area when the platform supports it. Include a magic value, reset cause, exception number, stack pointer, fault registers, program counter, link register, and a build identifier. Protect the record from being mistaken for valid data after a clean boot.
Cadence and checkpoints
Use the checklist at three levels: during each debugging session, at every release candidate, and on a monthly or quarterly maintenance cycle.
- Every crash: save the binary, map file, source revision, compiler options, reset cause, fault registers, and reproduction steps. Do not begin by changing several variables at once.
- Each feature or board port: rerun warning checks, inspect the map file, measure stack margins, test interrupt paths, and exercise error handling. Board changes can alter clock timing, memory placement, and peripheral behavior.
- Each release candidate: test high-load communication, maximum message sizes, repeated start-stop cycles, watchdog recovery, low-power transitions, and simultaneous interrupt sources. Record the smallest observed stack margin and any allocation failures.
- Monthly or quarterly: review recurring faults, reset-cause counts, watchdog events, assertion records, stack high-water marks, and unresolved static-analysis findings. Remove obsolete diagnostic code only after its replacement provides equivalent evidence.
Keep a short fault ledger with columns for date, firmware revision, hardware revision, trigger, observed registers, suspected cause, confirmed cause, and corrective test. This prevents the team from repeatedly investigating the same failure with different terminology.
typedef struct {
uint32_t magic;
uint32_t build_id;
uint32_t reset_cause;
uint32_t fault_status;
uintptr_t stacked_pc;
uintptr_t stacked_lr;
uintptr_t stacked_sp;
} fault_record_t;
The fields above are deliberately generic. Match their widths and meanings to the MCU, ABI, startup code, and debugger. A fault record is useful only if its capture path is itself reliable and does not depend on unavailable peripherals.
How to interpret changes
Look for patterns across builds and operating conditions. A rising fault count after a memory-layout change suggests checking the map file and adjacent buffers. A failure that moves when logging is added suggests timing sensitivity, stack use, or an uninitialized value; it does not prove that logging caused the bug. A program counter in a nonsensical region points toward a corrupted return address or function pointer, while a valid instruction address with a precise bus fault may indicate an invalid data access at a specific instruction.
When the fault occurs in a library or RTOS function, inspect the caller and inputs before blaming the library. The immediate faulting instruction may only be where earlier corruption becomes visible. Compare the stacked registers with the disassembly for the exact binary, and confirm that the debugger's symbols match that binary.
For intermittent races, replace large logging statements with compact event identifiers, timestamps, and sequence numbers. Logging inside a high-priority ISR can change the schedule and hide the problem. Where possible, use a trace buffer written with bounded, nonblocking operations and drained later by a lower-priority context.
Assertions should stop or quarantine invalid states close to their origin. Useful assertions check buffer lengths, state-machine transitions, queue results, alignment assumptions, and ownership rules. In production, route assertions to a controlled recovery path that preserves the reason and location without repeatedly rebooting in a loop.
For broader firmware workflow, a reproducible build layout helps ensure that the debugger, map file, and binary describe the same program. The CMake project structure guide provides related guidance for separating libraries, tests, and applications. If the failure involves a bus peripheral, pair this checklist with the CAN bus troubleshooting guide to distinguish firmware memory faults from physical-layer or protocol failures.
When to revisit
Revisit this checklist whenever a new MCU family, compiler version, RTOS configuration, linker script, board revision, optimization level, or memory model is introduced. Fault-register layouts, debug commands, cache behavior, startup code, and RTOS diagnostics can differ even when the application code remains unchanged. Treat those changes as new diagnostic assumptions to verify.
At the next monthly or quarterly review, compare the fault ledger with current measurements. Ask whether stack margins are shrinking, whether a reset cause is becoming more frequent, whether assertions are clustered around one subsystem, and whether a previously intermittent failure now has a narrower trigger. Update the fault handler, debugger notes, and test cases when the answer changes.
For the next incident, follow this practical sequence:
- Freeze the exact firmware, symbols, map file, hardware revision, and reproduction conditions.
- Read reset-cause and fault registers before clearing them.
- Validate the stacked program counter, link register, stack pointer, and surrounding memory.
- Check compiler warnings, map-file changes, stack margins, buffer boundaries, and ownership transitions.
- Use assertions, watchpoints, and a minimal event trace to turn the symptom into a precise write, read, or state transition.
- Confirm the fix with the original reproduction and a stress test that targets the suspected failure mode.
Keeping these measurements current turns embedded C debugging from a last-minute exercise into a repeatable engineering process. The most valuable result is not merely a repaired crash, but a smaller diagnostic gap the next time firmware fails.