GDB(五) 用GDB检查栈

10 篇文章 0 订阅

载入一个程序并设置一个断点

把之前的try1.c编译成可执行文件,并用gdb来载入

$ gdb try1
GNU gdb (Ubuntu/Linaro 7.3-0ubuntu2) 7.3-2011.08
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-linux-gnu".
For bug reporting instructions, please see:
<http://bugs.launchpad.net/gdb-linaro/>...
Reading symbols from /home/tommy/tmp/try1...done.
(gdb) 

(gdb)是GDB的输入提示。用run命令运行程序

(gdb) run
Starting program: /home/tommy/tmp/try1
In main():
   x is 5 and is stored at 0xbffff2a8.
   xptr points to 0xbffff2a8 which holds 5.
In display():
   z is 5 and is stored at 0xbffff290.
   zptr points to 0xbffff2a8 which holds 5.
[Inferior 1 (process 18365) exited normally]
我们可以用“break 行号”的方式来设置断点。比如break 5表示在第5行暂停,这时第4行已经执行,而第5行还没有。

(gdb) break 10
Breakpoint 1 at 0x8048475: file try1.c, line 10.
(gdb) run
Starting program: /home/tommy/tmp/try1
In main():
   x is 5 and is stored at 0xbffff2a8.
   xptr points to 0xbffff2a8 which holds 5.
Breakpoint 1, main () at try1.c:10
10       display(x, xptr);

backtrace命令简单地列出当前在栈上的框架

(gdb) backtrace
#0  main () at try1.c:10
接着可以用step命令执行下一行代码

(gdb) step
display (z=5, zptr=0xbffff2a8) at try1.c:15
15        printf("In display():\n");
再用backtrace看下栈上的框架:

(gdb) backtrace
#0  display (z=5, zptr=0xbffff2a8) at try1.c:15
#1  0x08048489 in main () at try1.c:10
一些要注意的地方:

1、我们现在有两个框架。框架1属于main()而框架0属于display()。

2、每个框架列项给出函数的参数。我们看到main没有参数,而display有,而且显示出了参数的值。

3、每个框架列项给出了框架里正被执行的行号。

4、框架的编号系统可能有点令人疑惑。main是1而display是0。这是为了个栈往下增长的概念一致。

不带参数的frame命令可以让GDB告诉我们现在在哪个框架里

(gdb) frame
#0  display (z=5, zptr=0xbffff2a8) at try1.c:17
17       printf("   zptr points to %p which holds %d.\n", zptr, *zptr);
当前的frame是0,我们可以访问在frame 0里的所有局部变量。相反,我们不能访问其它框架的自动变量。

我们可以用print打印display函数里的z和zptr变量

(gdb) print z
$3 = 5
(gdb) print zptr
$4 = (int *) 0xbffff2a8
但是我们不访问main里的变量:

(gdb) print x
No symbol "x" in current context.
(gdb) print xptr
No symbol "xptr" in current context.
我们可以使用frame命令来改变当前栈

(gdb) frame 1
#1  0x08048489 in main () at try1.c:10
10       display(x, xptr);
(gdb) print x
$5 = 5
(gdb) print xptr
$6 = (int *) 0xbffff2a8
(gdb) print z
No symbol "z" in current context.
(gdb) print zptr
No symbol "zptr" in current context.
顺便一提,程序的输出会和GDB的输出混在一起,容易造成混淆。需要花些时间来适应。

quit命令退出GDB。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值