Imagine a board that looked fine on the bench and then fails a few minutes into normal operation, after several hundred UART or CAN messages have already gone through. No line of code is obviously wrong. Your first reflex is to open the editor and change the part you suspect. This is where many debugging sessions go wrong, because the edit changes the timing, the memory layout or the exact sequence that triggered the bug, and afterwards you do not know whether you fixed the problem or only moved it. The same thing happens when a serial parser rejects one frame out of a long capture, when a Linux tool fails for one input file, or when a C++ lifetime bug shows up only with optimization switched on.
This article describes the order of work that I use in such cases: collect evidence first, narrow the fault down to one layer, and change code last. The examples are C and C++ for firmware and for host tools.
Capture the exact failure before editing code
While a failure is still vague, your first job is to describe it so that another engineer could reproduce it. For firmware, write down the board revision, the firmware build, the power condition, the communication sequence, the last reset reason and the state you observed. For a host tool, write down the command line, the input file, the operating system, the compiler flags and the last log lines. It takes five minutes, and it stops the symptom from changing its description every time somebody talks about it.
A captured symptom also tells you when you are finished. Say the original failure was a CRC error counter that went up after a USB reconnect. A cleaner parser or a longer timeout does not close this bug. You have to run the same reconnect sequence again, and the counters or the trace have to show that the path that failed before now works. The diagram below shows the workflow that the rest of this article follows.
Freeze the input that triggers the bug
A debugger is much more useful when the input stays the same. If your parser fails on one packet, keep that packet. If a production tester fails after a certain button sequence, save the sequence. If a string parser fails for one input, make a small replay case from it. Otherwise you try to understand a failure while the stimulus changes under you. Most tools can record the input for you: a logic analyzer exports the bytes, candump -l writes CAN traffic to a file, and Wireshark saves a TCP session.
The next snippet stores a failing frame as an array of bytes. The first two bytes use the protocol constants for the start byte and for the command under test, so that somebody who reads the test later can see whether it is about framing, command decoding, length handling or the checksum, without decoding raw numbers.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <array> #include <cstdint> constexpr std::uint8_t FRAME_START_BYTE = 0xA5u; constexpr std::uint8_t COMMAND_READ_STATUS = 0x12u; static constexpr std::array<std::uint8_t, 5> failing_packet{ FRAME_START_BYTE, COMMAND_READ_STATUS, 0x02u, 0x00u, 0x91u }; void replay_failing_packet(void) { // Good: the failing input is fixed in the code and can be replayed at any time. // Note: parser_accept_bytes() is the receive-path entry point under test. parser_accept_bytes(failing_packet.data(), failing_packet.size()); } |
The stored packet does not tell you where the defect is. It gives you and your team something fixed that can be replayed after every parser change, after a compiler update, or during a discussion about the bug.
Build a timeline from cheap trace records
Some failures are about order, and you can look at the final value for a long time without finding them, because the value is not wrong. Imagine a DMA callback that fires before the buffer has changed its owner, a timeout that expires at the moment the retry starts, or a worker thread that posts its result after the receiving object is already destroyed. In all three cases you need to know which event came first.
A short trace records enough to answer that question. In firmware it has to be cheap enough to run close to the failure without moving it. On a host tool you can afford richer logs or timestamps from a test harness, but the goal is the same: a short ordered list of events, which is more useful than a large unstructured log.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <stdint.h> typedef enum { TraceEvent_RxStarted, TraceEvent_RxComplete, TraceEvent_ParseStarted, TraceEvent_ParseRejected } TraceEvent; typedef struct { uint32_t timestamp_ms; TraceEvent event; } TraceEntry; #define TRACE_ENTRY_COUNT 32u static TraceEntry trace_entries[TRACE_ENTRY_COUNT]; // Note: volatile is for visibility only; this example assumes one writer. static volatile uint8_t trace_write_index; void trace_record(TraceEvent event) { // Note: read the volatile index once, so the fast path does a single load // and the entry slot and the increment below stay consistent with each other. const uint8_t write_index = trace_write_index; TraceEntry *entry = &trace_entries[write_index]; // Good: keep only ordered evidence, not formatted text in the fast path. // Note: HAL_GetTick() is the STM32 HAL millisecond tick; any monotonic // tick source works here. entry->timestamp_ms = HAL_GetTick(); entry->event = event; trace_write_index = (uint8_t)((write_index + 1u) % TRACE_ENTRY_COUNT); } |
You read the trace with the debugger. Stop at a breakpoint in the fault handler or at the place where the error is detected, and print trace_entries in GDB shows the last 32 events with their times. A small ring has one clear limit: old entries are overwritten. That is fine when the failure happens shortly after its trigger. For faults that take hours to appear, use a larger buffer or stop recording when a fault flag is set, so that the interesting entries survive.
The example also depends on the execution context. volatile stops the compiler from caching the write index, but it does not make the update of the index atomic. If an interrupt handler and a task can both write trace entries, let only one of them write, disable interrupts around the index update, or use an atomic operation that your target supports. On Cortex-M parts with the right debug hardware, ITM/SWO or ETM trace through the debug probe can give better timing data than more software trace records.
Instrument the boundary where the state changes
Every time data changes its form, the kind of possible fault changes too. Bytes become frames, frames become commands, commands change a state, and the state produces outputs. Linux utilities and Qt tools have the same structure: files become records, records become model objects, and model objects drive a display or a report. If you put your counters and trace points at these crossings, you learn much more than from print statements in every function along the call path.
It helps to draw a map of these crossings before you add instrumentation. The blocks differ from project to project, but the useful counters are almost always at the places where the owner of the data, the timing, the format or the level of trust changes.
Change one condition at a time
Imagine you increase a timeout, add a delay and enlarge a buffer in the same test run, and the symptom disappears. You still do not know which of the three changes mattered, or whether the combination only hides the failure. When several experiments are mixed, you lose the connection between cause and effect.
A temporary compile-time switch lets you test one theory without mixing it with other edits. It should look temporary, and after the experiment you either remove it or turn it into a real configuration option with a reason. In the snippet only the sensor timeout changes, and the production value stays visible next to it.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#define DEBUG_TEST_LONGER_SENSOR_TIMEOUT 0u static uint32_t sensor_ready_timeout_ms(void) { #if DEBUG_TEST_LONGER_SENSOR_TIMEOUT // Tradeoff: temporary experiment to test whether timing is the failure cause. return 100u; #else // Good: production path keeps the original measured timeout. return 20u; #endif } |
Testing one condition at a time feels slow when everybody has three ideas they want to try at once, but each result then means something. If the failure appeared between two known builds, git bisect does the same thing for you automatically: it tests one commit at a time until the change that introduced the failure is found.
Use one counter for each kind of failure
One error counter is rarely enough in firmware or protocol code. A frame that is too short, a wrong start byte, a bad CRC and a rejection by the application all look like “receive failed” from outside, but they have different causes. If you add them into one number, you can no longer see in which layer the first thing went wrong.
In the example, 0xA5u is the sync byte of the protocol. The check uses the constant FRAME_START_BYTE from the earlier snippet, so the failure path contains no bare number.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
struct DecodeStats { unsigned frames_seen = 0; unsigned frames_accepted = 0; unsigned frames_too_short = 0; unsigned frames_bad_start = 0; unsigned frames_null_input = 0; }; bool decode_frame(const std::uint8_t* data, unsigned length, DecodeStats& stats) { ++stats.frames_seen; if (data == nullptr) { // Good: a null pointer is a caller bug, not a short frame; count it separately. ++stats.frames_null_input; return false; } if (length < 4u) { // Good: short input is counted as its own failure class. ++stats.frames_too_short; return false; } if (data[0] != FRAME_START_BYTE) { // Good: wrong sync byte is separated from short input. ++stats.frames_bad_start; return false; } ++stats.frames_accepted; return true; } |
Do not let the counters grow into a second interface that has to be maintained. Start with the crossings that decide your next debugging step: transport, framing, validation, state transition and rejection by the application.
Make invalid states report themselves
C and C++ systems often fail long after the first invalid state appeared. Suppose a state machine accepts a transition that it should reject, or a driver accepts a command although the shutdown has already started. If the code accepts such a state without any record, the symptom you finally see can look unrelated to the cause.
The state machine below has only a few legal transitions. The helper counts every unexpected one, so the state cannot break its rules without leaving a trace.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
typedef enum { MotorState_Idle, MotorState_Starting, MotorState_Running, MotorState_Fault } MotorState; static volatile unsigned invalid_transition_count; static void record_invalid_transition(void) { // Tradeoff: use an atomic increment or critical section if several contexts call this path. ++invalid_transition_count; } bool motor_transition_allowed(MotorState from, MotorState to) { if (from == MotorState_Idle && to == MotorState_Starting) { return true; } if (from == MotorState_Starting && to == MotorState_Running) { return true; } // Note: a real motor needs a normal stop path, not only a fault exit. if (from == MotorState_Running && to == MotorState_Idle) { return true; } // Note: recovery to Idle is allowed only after the fault cause is handled. if (from == MotorState_Fault && to == MotorState_Idle) { return true; } if (to == MotorState_Fault) { return true; } // Good: unexpected paths leave evidence during bring-up. record_invalid_transition(); return false; } |
In safety-related or production firmware, an invalid transition may need more than a counter: a fault state, a diagnostic record or a controlled reset. During bring-up a counter is often enough, because it shows that the state model was violated before the visible failure happened.
The counter is only diagnostic, but it has to follow the same concurrency rules as all other shared data. If all transition requests go through one control task, a normal counter is enough. If requests can come from an interrupt handler, from several tasks or from several cores, the counter needs an atomic increment or a short critical section. Without it, the diagnostic code can lose counts while it tries to report the bug.
Keep logging out of timing-critical paths
More logging has a price in embedded systems. A log statement changes the timing, uses stack, can block on a UART and can allocate memory. At 115200 baud one character takes about 87 µs, so a blocking print of a 30-character line holds the code for 2.6 ms. That is enough to hide the race condition you are looking for, or to create a new one. On a desktop the costs are different, but a log line can still move a concurrency bug, because it changes the scheduling of the threads.
For timing-sensitive code, decide first which information must be recorded in the fast path and which work can wait. Event counters, compact trace records, a GPIO pin that you toggle and watch on an oscilloscope, and status snapshots are all much cheaper than formatted text inside an interrupt handler, a control loop or a fast receive callback.
The counter example below uses two wrapper functions for a critical section. In a real project they save and restore the interrupt state, enter an RTOS critical section, or are replaced by an atomic operation. The reason is the same as before: volatile only makes the variable visible, and ++counter is still a read, an add and a write that an interrupt, another task or a second core can interrupt.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
typedef enum { DebugEvent_RxByte = 0u, DebugEvent_FrameAccepted = 1u, DebugEvent_FrameRejected = 2u, DebugEvent_Count } DebugEvent; typedef unsigned DebugIrqState; DebugIrqState debug_enter_critical(void); void debug_exit_critical(DebugIrqState state); static volatile unsigned debug_event_counts[DebugEvent_Count]; void debug_count_event(DebugEvent event) { if ((unsigned)event >= (unsigned)DebugEvent_Count) { return; } // Good: protect the read-modify-write if several contexts can update it. DebugIrqState state = debug_enter_critical(); ++debug_event_counts[(unsigned)event]; debug_exit_critical(state); } |
Such small records give you less context than a full log. Accept that at first, because the behavior of the system stays the same. When you know the suspicious crossing, add richer output in a slower task, in a replay on the host or in a test harness.
In host-side C++, std::atomic<unsigned> is the clearest way to write a shared debug counter. In C firmware you can use C11 atomics or compiler builtins such as __atomic_fetch_add, but check what your MCU, compiler and runtime make of them. On small MCUs a short critical section is often more predictable than the hope that the compiler produced a lock-free instruction.
Check lifetime and ownership before rewriting logic
In C++ a value can be logically right and still be invalid. Imagine a failure that changes when you switch the optimization level, add a log line or change an allocation. This behavior is typical for lifetime bugs: a view of a string that no longer exists, a reference to a temporary object, an iterator that was invalidated, a callback that lives longer than its owner, or a span that was kept after its buffer was freed. Check the lifetimes early in such a case, before you rewrite any logic.
The example uses a status string. Returning a view of a local string is wrong, because the string is destroyed when the function returns. Returning a view of static storage is safe here, because that storage exists for the whole program run.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <string> #include <string_view> std::string_view bad_status_text(void) { std::string text = "fault"; // Bad: the string dies before the returned view is used. return text; } std::string_view good_status_text(void) { static constexpr char text[] = "fault"; // Good: the returned view refers to static storage. return text; } |
Which fix is right depends on the interface. Static storage works for fixed text and is no solution for dynamic data. In the other cases the caller should own a std::string, or the function should write into a buffer that the caller provides, or the interface should say clearly who owns the data.
Sanitizer builds on the host find this class of bug quickly. AddressSanitizer (ASan) catches many use-after-free errors and stack lifetime errors, and UndefinedBehaviorSanitizer (UBSan) reports several kinds of undefined behavior. With GCC or Clang, compile and link with -fsanitize=address,undefined -g and run your tests. The sanitizers do not replace tests on the target and usually cannot run on bare-metal firmware, but for parser logic, protocol code, libraries and simulation builds that run on a PC they are very effective.
Use assertions for broken assumptions
Some checks are about assumptions of the design and have nothing to do with errors that can happen in normal operation. An assertion is right when a violation means that the surrounding code is wrong, and it is most useful in debug builds, test tools, simulation builds and during firmware bring-up. The question to ask is whether the system can recover. Bad input from outside should be handled. An internal condition that can never be false in correct code should stop loudly when it is false.
In the example, the capacity of the ring buffer must be a power of two, because the wrap uses a bit mask. The static assertion puts this requirement into the code, where the compiler checks it, and it no longer lives only in a design note. The runtime assert covers the second kind of assumption, one that exists only while the code runs: the index must already be wrapped when it reaches the store function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <cassert> #include <cstdint> constexpr unsigned RX_RING_CAPACITY = 128u; constexpr unsigned RX_RING_MASK = RX_RING_CAPACITY - 1u; static_assert((RX_RING_CAPACITY & RX_RING_MASK) == 0u, "RX ring capacity must be a power of two"); static std::uint8_t rx_ring[RX_RING_CAPACITY]; unsigned wrap_rx_index(unsigned index) { // Good: this wrap is valid because the static assertion proved the shape. return index & RX_RING_MASK; } void rx_ring_store(unsigned index, std::uint8_t value) { // Good: the runtime assert catches an out-of-range index in debug and test builds. assert(index < RX_RING_CAPACITY); rx_ring[index] = value; } |
The standard assert() disappears when NDEBUG is defined, which is the default of most release builds. On small targets, decide which assertions stay in production and what they do when they fire. Some products can stop in a fault state, some need a diagnostic record and a reset, and some must continue with reduced function. This decision should follow the risk of the system.
Reduce the failing path to one test
When the frozen input and the counters point to a small area, make a test from it. The test does not have to model the whole product. It only has to keep the properties that make the bug appear, so that you can check the fix again after the next edit.
The next test checks that a short frame is counted as short and is not counted as a wrong start byte. The difference matters because each counter points to a different layer of the receive path.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <cassert> void test_short_frame_is_not_bad_start(void) { DecodeStats stats{}; const std::uint8_t short_frame[] = { FRAME_START_BYTE, COMMAND_READ_STATUS }; const bool ok = decode_frame(short_frame, 2u, stats); // Good: the test checks the exact failure classification. assert(ok == false); assert(stats.frames_too_short == 1u); assert(stats.frames_bad_start == 0u); } |
A small test does not replace the check on hardware. It removes one source of uncertainty before you go back to the board, the test fixture or the customer capture. For firmware the usual way is to replay the parser or the state logic on the host first, and then to run the original hardware sequence again with the changed code.
Verify the fix against the original symptom
A fix is finished when the original symptom is gone and your evidence shows that the intended path is now used. Cleaner code or a passing test nearby is not enough. Keep the original packet, the test sequence, the input file or the hardware setup until you have done this check.
The table sums up the habits from this article, together with the evidence each one produces. If a debugging step produces no new evidence, it is probably not bringing you closer to the cause.
| Habit | Evidence it creates | Failure it prevents |
|---|---|---|
| Capture the exact symptom | Known start and end condition | Debugging a changing story |
| Freeze failing input | Repeatable stimulus | Chasing a moving packet, file, or state |
| Build a timeline | Ordered events | Confusing order bugs with value bugs |
| Instrument boundaries | Layer-specific evidence | Scattering logs without narrowing the fault |
| Change one condition | Experiment with causality | Lucky fixes with unknown mechanism |
| Count failure classes | Transport, format, or state distinction | One vague error counter |
| Use bounded instrumentation | Timing-safe clues | Measurement changing the failure |
| Check lifetime early | Ownership and validity evidence | Rewriting logic around a dangling object |
| Add a focused test | Regression protection | A fix that only works once |
Practical takeaways
In C and C++ systems, most of the useful debugging work happens before the first code change: capture the failure, freeze the input, find the crossing where correct state becomes incorrect, and choose instrumentation that does not change the timing or the lifetimes you are measuring. When the cause is isolated, reduce it to a small test if you can, and then check the fix with the original symptom on the real target or the real input. In the first ten minutes this feels slower than guessing. It pays off as soon as the failure involves firmware timing, protocol layers, object lifetime or production hardware, where trial and error does not get you far.