原文件编译的时候要加-g,例gcc -g -o test test.c, 这样在能在调试的时候用list,watch等命令。
全局变量或当前堆栈区可见的变量才能watch,watch之后用Continuing,就可显示观察变量。
gdb watch 跟踪变量的变化
01 #include <stdio.h>
02 #include <stdlib.h>
03 #include <string.h>
04
05 int main()
06 {
07 char * name = NULL;
08 int len = 10;
09
10 name = (char *)malloc(len);
11 strncpy(name, "zengxiaolong", len);
12
13 char ** wild_pointer;
14 wild_pointer = &name; // 野指针,指向了变量name
15 *wild_pointer = (char *)0x100; // 野指针,破坏了变量name
16
17 name[0] = 'a';
18 return 0;
19 }
# gcc test.c -o test -g
# gdb -q test
(gdb) l
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 int main()
6 {
7 char * name = NULL;
8 int len = 10;
9
10 name = (char *)malloc(len);
(gdb) b 7
Breakpoint 1 at 0x80483b5: file test.c, line 7.
(gdb) r
Starting program: /tftpboot/test
Breakpoint 1, main () at test.c:7
7 char * name = NULL;
(gdb) watch name // 跟踪变量name变化情况
Hardware watchpoint 2: name // 说明该系统结构支持硬件断点
(gdb) c
Continuing.
Hardware watchpoint 2: name
Old value = 0xb7f79dc0 "U\211�WVS��y" // 这里变量name发生了变化
New value = 0x804a008 ""
main () at test.c:11
11 strncpy(name, "zengxiaolong", len);
(gdb) c
Continuing.
Hardware watchpoint 2: name
Old value = 0x804a008 "zengxiaolo"
New value = 0x100 <Address 0x100 out of bounds> // 指针越界了
main () at test.c:17
17 name[0] = 'a';
(gdb) c
Continuing.
Program received signal SIGSEGV, Segmentation fault.
0x080483fd in main () at test.c:17
17 name[0] = 'a';
(gdb)