我定义了一个结构,它在运行时分配。我想在其值更改时在其上设置断点。 我已经看到了答案,但它们没有考虑动态分配的变量。
在 gdb 中观看。我尝试动态查找它,但在预定义变量上发现,可以通过 gdb 找到内存,然后对该内存地址进行检查。
我很好奇,所以这里有一个示例程序:
#include <stdio.h>
#include <stdlib.h>
struct foo {
int bar;
};
int main() {
struct foo *foo = malloc(sizeof *foo);
foo->bar = 42;
printf("bar=%d\n", foo->bar);
foo->bar = 1;
printf("bar=%d\n", foo->bar);
free(foo);
}
以及使用 watch 的 gdb 会话:
(gdb) start
Temporary breakpoint 1 at 0x1161: file 1.c, line 9.
Starting program: /home/allan/a.out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Temporary breakpoint 1, main () at 1.c:9
9 struct foo *foo = malloc(sizeof *foo);
(gdb) watch foo->bar
Hardware watchpoint 2: foo->bar
(gdb) c
Continuing.
Hardware watchpoint 2: foo->bar
Old value = -134434816
New value = 0
main () at 1.c:10
10 foo->bar = 42;
(gdb) c
Continuing.
Hardware watchpoint 2: foo->bar
Old value = 0
New value = 42
main () at 1.c:11
11 printf("bar=%d\n", foo->bar);
(gdb) c
Continuing.
bar=42
Hardware watchpoint 2: foo->bar
Old value = 42
New value = 1
main () at 1.c:13
13 printf("bar=%d\n", foo->bar);
(gdb) c
Continuing.
bar=1
Hardware watchpoint 2: foo->bar
Old value = 1
New value = 1431655769