Table of Contents

GDB Watching Expressions

Watches pause execution when a variable changes value. Displays auto-print a value every time execution pauses. Together they monitor state without repeatedly typing print commands.

(gdb) watch x                   # pause when x changes
(gdb) watch arr[5]              # pause when arr[5] changes
(gdb) watch *ptr                # pause when dereferenced pointer changes
(gdb) info breakpoints          # list watches (shown as "watchpoint")
(gdb) delete 1                  # delete watchpoint 1
(gdb) display x                 # auto-print x at each pause
(gdb) display x + y             # auto-print expression
(gdb) info display              # list active displays
(gdb) delete display 1          # remove display 1
(gdb) undisplay 1               # alternative to delete display

Watchpoints use hardware or software to detect writes to a variable. When the value changes, execution pauses as if a breakpoint was hit. You can then inspect the new value, the stack, etc. Useful for finding where a variable got corrupted.

Displays print a variable or expression automatically whenever GDB pauses—at breakpoints, after stepping, etc. No need to type print x repeatedly. Display references are separate from breakpoint numbers. Useful for tracking a variable across many steps without cluttering the output.

Watches can slow execution significantly (especially software watchpoints). Use them to find specific bugs (e.g., “find where this pointer gets set to NULL”), then remove them.

Not all architectures support hardware watchpoints. GDB falls back to software watchpoints, which are slower. A message like Hardware watchpoint 1 / Software watchpoint 1 indicates which was used.

Combining watches and displays: watch to pause on changes, display to show the new value automatically. Together they pinpoint where unwanted state changes occur.