打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
GDB(五)--用GDB检查栈
标签GDB 分类: GDB


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

把之前的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。
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
使用 GDB 调试 Linux 软件
Linux环境下的堆栈
C++ 常量折叠和C语言中const常量对比
从汇编的角度分析C语言(一)char *p与char p[]的区别
main之前
通过3个程序分析数组与指针区别
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服