Frank Vilea
Frank Vilea

Reputation: 8487

GDB: Assign breakpoint to change of symbol

I'm debugging a C application that has a segmentation fault. I already identified the variable that causes the problem. However, I do not know yet, when the variable is assigned so that it causes the Segmentation Fault.

Is there a way to set a breakpoint in GDB if a new value is being assigned to an existing variable?

Upvotes: 4

Views: 420

Answers (2)

pmg
pmg

Reputation: 108978

#include <stdio.h>

struct foo {
  int i[12];
  int j;
};

int main(void) {
  struct foo foo = {{0}};
  int *p;

  p = foo.i;
  p[12] = 42;
  printf("j is %d\n", foo.j);
  return 0;
}
gdb ./a.out
[...]
Reading symbols from a.out...done.
(gdb) break main
Breakpoint 1 at 0x40052c: file 6469109.c, line 9.
(gdb) run
Starting program: a.out 

Breakpoint 1, main () at 6469109.c:9
9         struct foo foo = {{0}};
(gdb) watch foo.j
Hardware watchpoint 2: foo.j
(gdb) cont
Continuing.
Hardware watchpoint 2: foo.j

Old value = -7936
New value = 0
0x0000000000400545 in main () at 6469109.c:9
9         struct foo foo = {{0}};
(gdb) cont
Continuing.
Hardware watchpoint 2: foo.j

Old value = 0
New value = 42
main () at 6469109.c:14
14        printf("j is %d\n", foo.j);
(gdb) quit
A debugging session is active.

        Inferior 1 [process 572] will be killed.

Quit anyway? (y or n) y

Upvotes: 5

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84169

You need a watchpoint:

(gdb) watch my_var

Upvotes: 5

Related Questions