Use a watchpoint on the variable. Since the symptom is that the global is mysteriously getting a wrong value but you don't know where the bad write occurs, a breakpoint is useless, you'd have nowhere to put it. Instead you set a write watchpoint on the variable's address (watch g_var in GDB), then continue; the debugger halts at the exact instruction that writes the variable, reporting the old and new values, and a backtrace (bt) shows the call chain that performed the write, immediately identifying the culprit, whether it's a wild pointer, a buffer/stack overflow writing past its bounds, or a logic bug in an unexpected function. This is dramatically faster than scattering prints or guessing. On a Cortex-M these use the DWT (Data Watchpoint and Trace) unit's hardware comparators, so they catch the write at full speed without instrumenting the code, though there are only a few available. Caveats to mention: a watchpoint on a stack/local variable becomes invalid once that frame is gone, so this works best on globals or known fixed addresses; and the DWT watches the CPU's bus accesses, so if a DMA controller or another bus master is the one writing the address, a CPU watchpoint may not trigger and you'd need a different approach (e.g., watching the DMA configuration, or memory protection). But for the common "a CPU instruction somewhere is clobbering this global," a write watchpoint plus backtrace is the canonical, fastest tool.
Debugging & Toolchain · Interview question
How would you find what's corrupting a global variable?
A strong answer
What a weak answer sounds like
You know the answer. Do you know what gets you dinged?
Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.
From the lesson
Breakpoints & Watchpoints
Stop on a line vs stop on a data change: software vs hardware breakpoints (and why flash execution forces the limited hardware kind), and watchpoints, the tool for catching memory corruption.