Break when a variable changes with watch in GDB
Stop GDB the moment a variable's value changes with watch, which uses a hardware watchpoint and reports the old and new value.
Stepping line by line to find who corrupts a counter is slow. watch tells GDB to stop whenever the value of an expression changes, and it reports the line that did it. On x86-64 Linux, GDB 16 uses a hardware watchpoint when the debug registers allow it, so the program runs at close to full speed until the write happens.
// count.c, built with: gcc -g -O0 count.c -o count
#include <stdio.h>
int total;
void add(int n) { total += n; }
int main(void) {
for (int i = 1; i <= 3; i++) add(i);
printf("%d\n", total);
return 0;
}(gdb) break main
(gdb) run
(gdb) watch total
Hardware watchpoint 2: total
(gdb) continue
Hardware watchpoint 2: total
Old value = 0
New value = 1
add (n=1) at count.c:4
4 void add(int n) { total += n; }The stop is reported after the writing instruction has run, so the line shown is the statement that changed the value, or the one right after it. Watching a local variable works too, but GDB deletes that watchpoint when the frame exits. A watch on something larger than the hardware can cover falls back to software single-stepping, which is slow enough that you will notice. See the GDB manual on watchpoints.