在C中动态分配的结构中的变量上设置写断点

ruarlubt  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(79)

我定义了一个结构,它在运行时被分配。我想在它的值被改变时在它上面设置一个断点。我已经看到了答案,但他们没有考虑动态分配的变量。
在gdb中观察。我试着动态地寻找它,但发现它在预定义的变量上,内存可以通过gdb找到,然后设置对该内存地址的检查。

332nm8kg

332nm8kg1#

我很好奇,所以这里有一个例子程序:

#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

相关问题