Skip to content
systemcoding.dev
Debugging

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.

1 min read
Summarize in AI

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.

c
// 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;
}
Text
(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.

Taggedclinuxgdb
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.