Course contentsShow
← C
Lesson 836 of 1,21911. The Preprocessor and BuildFree lesson

Using `watch` for memory changes

Using watch for memory changes

What you'll learn: How to pause your program automatically the exact moment a variable's value changes using GDB hardware breakpoints.

The Problem: The "Who Touched That?" Mystery

Imagine you have a variable, like a player’s health or a configuration flag, that is suddenly changing to an impossible value. You know what the value is, but you don't know when or where in your 500 lines of code the change happened.

Normally, you might step through the code line-by-line using next, which is like watching a 24-hour security tape at 1x speed. It’s tedious and prone to human error. Instead, you need an alarm that trips the second someone touches that specific memory address.

The Solution: Hardware Watchpoints

In GDB, the watch command sets a "watchpoint." Unlike a breakpoint (which stops at a specific line of code), a watchpoint stops the program whenever the value of a specific expression or variable changes.

To use it, you first start GDB and run your program until the variable you want to track is "in scope" (usually by setting a breakpoint at the start of main).

#include <stdio.h>

int main() {
    int target = 10;
    int items[3] = {1, 2, 3};

    // Imagine a complex loop or hidden logic here
    for (int i = 0; i <= 3; i++) {
        items[i] = 0; // Bug: Out-of-bounds access hits 'target'
    }

    printf("Target is now: %d\n", target);
    return 0;
}

How to use it in GDB

  1. Start the debugger: gdb ./my_program
  2. Start execution: Type start to pause at the beginning of main.
  3. Set the watchpoint: Type watch target. GDB will confirm it has created a hardware watchpoint.
  4. Continue execution: Type continue (or c).

The program will run at near-full speed until the value of target changes. GDB will then freeze the program and show you the "Old value" and the "New value," pointing exactly to the line of code that caused the modification. In the code example above, GDB would stop on the line items[i] = 0; the moment i reached 3, revealing a buffer overflow that accidentally overwrote the target variable.

When to use it

Use watch when you have a global variable being corrupted by unknown functions, or when a pointer is overwriting memory it doesn't own. It is the ultimate tool for catching "silent" bugs that don't cause an immediate crash but lead to incorrect data later.

Key takeaway

Use watch <variable> in GDB to automatically pause execution the instant a variable’s value is modified.