How to Use GDB Watchpoints to Catch Memory Modifications in C/C++
This guide explains why memory bugs are hard to locate in C/C++ programs, introduces GDB watchpoints as a way to monitor specific memory addresses, and walks through a complete example—including source code, compilation, breakpoint setting, watchpoint creation, and interpreting the hardware watchpoint output—to pinpoint the exact line that modifies a variable.
Why Memory Bugs Are Tricky
In C/C++ programs manual memory management provides high performance but also makes bugs hard to locate because the symptom often appears far from the actual cause.
Using GDB Watchpoints
GDB can set a watchpoint that stops execution whenever a specified memory location is read or written, allowing you to pinpoint the exact instruction that modifies the data.
Example Program
#include <iostream>
#include <thread>
using namespace std;
// Thread that modifies a variable
void memory_write(int* value) {
*value = 1;
}
int main() {
int a = 10;
// Get address of local variable a
int* c = &a;
for (int i = 0; i < 100; i++) {
a += i;
}
cout << a << endl; // prints 4960
// Pass the address to a thread that will modify it
thread t(memory_write, c);
t.join();
return 0;
}The program creates a local variable a, prints its value (4960), then spawns a thread that changes a to 1 via the pointer c.
Debugging Steps with GDB
Compile with debugging symbols and thread support: g++ -g a.cc -o a.out -pthread Start GDB: gdb a.out Set a breakpoint at the line that prints a (line 20 in the example): (gdb) b a.cc:20 Run the program: (gdb) r Print the address of a to obtain the exact memory location:
(gdb) p &a
$1 = (int *) 0x7fffffffe508Set a hardware watchpoint on that address (assuming int is 4 bytes): (gdb) watch *(int*)0x7fffffffe508 Continue execution: (gdb) c When the thread writes to a, GDB stops and reports:
Hardware watchpoint 2: *(int*)0x7fffffffe508
Old value = 4960
New value = 1
memory_write (value=0x7fffffffe508) at a.cc:8This output shows the previous value, the new value, and the exact source line ( a.cc:8) where the modification occurred.
Key Takeaways
Watchpoints let you monitor a specific memory region without adding logging code.
Hardware watchpoints are efficient because the CPU tracks the address directly.
Using GDB watchpoints is especially useful for tracking down memory‑related bugs in multithreaded C/C++ programs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
