1 说明
print指令可以查看某个变量的值或者地址。
print的用法为:
print /fmt expression
其中,fmt表示显示的格式,如下:
指令 | 说明 |
---|---|
x | 16进制 |
d | 有符号的10进制,默认格式 |
u | 无符号的10进制 |
o | 8进制 |
t | 2进制 |
a | 地址 |
c | 字符 |
f | 浮点 |
s | 字符串 |
expression 是指变量、函数等表达式。
print可以简写为p
2 代码准备
使用如下代码进行测试
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
int j = 0;
int test2()
{
char* s8Buf = NULL;
strcpy(s8Buf, "8888");
return 0;
}
int main()
{
int i = 0;
for (i = 0; i < 60; i++)
{
j++;
printf("-------->index %d\n", i);
sleep(1);
}
test2();
return 0;
}
3 指令测试
3.1 显示某个变量的值 print /d i
如下,显示变量j的值。
(gdb) start
Temporary breakpoint 1 at 0x40058f: file test_gdb.c, line 19.
Starting program: /home/test_demo/gdb/test_gdb
Temporary breakpoint 1, main () at test_gdb.c:19
19 int i = 0;
(gdb) print /d j
$1 = 0
(gdb)
3.2 显示某个变量的地址 print /a &i
如下,显示变量j的地址。
(gdb) print /a &j
$3 = 0x601044 <j>
4 高级用法
更多高级用法,请参考GDB官方说明
https://sourceware.org/gdb/current/onlinedocs/gdb/Data.html#Data
5 display
display指令用法和print完全一样,他们的区别是,使用display后,每次在碰到断点时候会主动打印display设置的命令,这样不用每次都要使用print,方便省事。
如下,每次碰到断点时候,打印变量j的值:
(gdb) break 23
Breakpoint 1 at 0x40059f: file test_gdb.c, line 23.
(gdb) start
Temporary breakpoint 2 at 0x40058f: file test_gdb.c, line 19.
Starting program: /home/test_demo/gdb/test_gdb
Temporary breakpoint 2, main () at test_gdb.c:19
19 int i = 0;
(gdb) display /a j
1: /a j = 0x0
(gdb) c
Continuing.
Breakpoint 1, main () at test_gdb.c:23
23 j++;
1: /a j = 0x0
(gdb) c
Continuing.
-------->index 0
Breakpoint 1, main () at test_gdb.c:23
23 j++;
1: /a j = 0x1
(gdb) c
Continuing.
-------->index 1
Breakpoint 1, main () at test_gdb.c:23
23 j++;
1: /a j = 0x2
(gdb) c
Continuing.
-------->index 2
Breakpoint 1, main () at test_gdb.c:23
23 j++;
1: /a j = 0x3
(gdb) c
Continuing.
-------->index 3
Breakpoint 1, main () at test_gdb.c:23
23 j++;
1: /a j = 0x4
(gdb)