Reputation: 516
#include <stdio.h>
typedef struct ThingStruct {
int arr[8];
int after;
} Thing;
void foo(int i) {
Thing thing;
int* ip = &thing.after;
thing.after = 12345;
printf("beforehand\n");
thing.arr[i] = 55;
printf("done\n");
}
int main() {
foo(8);
}
This code changes thing.after
by accidentally going off the end of the array. I want to try to find the line where where thing.after
is changing by using gdb. So I compile with -g , put a breakpoint on line 12, then put a watchpoint on thing.after
, but the watchpoint doesn't trigger, even though putting a breakpoint on line 14 does show that thing.after
did change.
I even tried taking the address of thing.after
and setting a watchpoint on that, but it still does not trigger.
Upvotes: 2
Views: 2459
Reputation: 213526
You didn't say which platform, what version of GDB, or what command you used to set the watchpoint.
Using gdb 7.9 on Ubuntu/x86_64, things work as I expect them to work:
(gdb) b foo
Breakpoint 1 at 0x400538: file t.c, line 10.
(gdb) r
Starting program: /tmp/a.out
Breakpoint 1, foo (i=8) at t.c:10
10 int* ip = &thing.after;
(gdb) watch thing.after
Hardware watchpoint 2: thing.after
(gdb) c
Continuing.
Hardware watchpoint 2: thing.after
Old value = 4195712
New value = 12345
foo (i=8) at t.c:12
12 printf("beforehand\n");
(gdb) c
Continuing.
beforehand
Hardware watchpoint 2: thing.after
Old value = 12345
New value = 55
foo (i=8) at t.c:14
14 printf("done\n");
(gdb) q
Upvotes: 1
Reputation: 2420
Watch point needs to be re-added each time the foo
function is entered (Note that, as you are watching the local variable, it will not be valid after the stack frame exits and will be automatically deleted after the foo
returns). Also, if the watched variable changes on the current line to be executed, then the watch point is not getting triggered (not sure why). For me it works when I add the watch point watch thing.after
just after entering foo when on line int* ip = &thing.after;
. When I continue, the watch point hits 2 times.
Upvotes: 3