您的位置:首页 > 其它

如何使用gdb调试程序

2008-12-17 15:04 731 查看
 如何使用gdb调试程序 调试程序对于编程的重要性,绝不亚于一天三餐对于人生命的重要性。
 调试程序以前,首先需要编译并连接你的源代码,但需要特别注意一点,就是需要在声称的可执行文件中加入调试信息,即gcc编译连接是加入-g选项。eg:gcc -g file.c -o file
 也可以使用gcc的-ggdb选项生成更多的调试信息,它可以访问你所连接的每一个库的源代码。虽然这个选项在某些情况下非常有用,但是大大浪费了磁盘空间(我测试一个很小的程序,发现并没有什么变化,可能当程序比较大,调用其他库函数的时候会有区别吧),在大多情况下,普通的-g选项就可以了。
 好了,废话少说,开始练练手吧。
 首先我编写了一个小程序存入debugme.c中。如下:
#include <stdio.h>
#define BIGNUM 5000
void index_to_the_moon(int ary[])
{
        int i;
        for(i=0;i<BIGNUM;i++)
                ary[i]=i;
}
int main(void)
{
 int intary[100];
 index_to_the_moon(intary);
return 0;
} 其实这个程序很简单,一看就可以看出来有一个内存越界的问题。那么我们就让gdb来看看如何发现这个错误吧。
使用
gcc -g debugme.c -o debugme
编译并连接这段程序。如果直接键入./debugme 执行这个可执行文件,可以发现有segmentation fault (翻译成汉语就是段错误,其实就是内存访问冲突阿)
我们用gdb来调试一下
输入如下命令 
gdb debugme 
终端会出现如下:
GNU gdb Red Hat Linux (6.5-15.fc6rh)
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...Using host libthread_db library "/lib/libthread_db.so.1".(gdb) 
 这就算是进入了gdb环境了。那么我们使用命令run运行一下看看结果如何?
Starting program: /home/zhxfan/debugmeProgram received signal SIGSEGV, Segmentation fault.
0x08048341 in index_to_the_moon (ary=0xbfbe5924) at debugme.c:7
7                       ary[i]=i;
 这段清单表明了错误类型 为Segmentation fault,发生在debugme.c的第7行代码ary[i]=i;处,错误出现的地址为0x08048341。
 既然出现了错误,那么我们就设置断点进行调试吧。我们在main函数的第一行设定断点,即文件的第11行:
break 11
 出现如下信息
Breakpoint 1 at 0x8048366: file debugme.c, line 11.
 不用解释了吧?
 然后就是单步跟踪了。首先使用run命令运行至断点处
Starting program: /home/zhxfan/debugmeBreakpoint 1, main () at debugme.c:12
12              index_to_the_moon(intary);
 然后采用step命令单步跟踪
index_to_the_moon (ary=0xbfd8aad4) at debugme.c:6
6               for(i=0;i<BIGNUM;i++)
 按回车键运行下一句 
7                       ary[i]=i;
 采用print i查看i的值
$1 = 0
 printf ary[i]
$2 = 0
 继续 run 
The program being debugged has been started already.
Start it from the beginning? (y or n) n
Program not restarted.
 会提示是否从开始处运行,选择n,即继续向下调试。
 重复step 回车
 print i
$3 = 1
 print ary[i]
$4 = 2
 继续重复以上命令即可完成简单的调试过程。关于gdb的其他命令以后再继续介绍。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: