main.c文件
#include <stdio.h>
void test()
{
int *ptr=NULL;
*ptr=10;
}
int main(int argc,char** argv)
{
test();
return 0;
}
加上编译选项-g O2可以定位到具体某一行
编译:gcc -g -O2 main.c
生成:./a.out
这个代码运行起来是会报 segmentation fault(core dumped) ,显然问题是给一个空指针赋值了
接下来我们来采用gdb调试这个问题
输入:gdb ./a.out
zienon@zienon-virtual-machine:segmentation$ gdb ./a.out
GNU gdb (Ubuntu/Linaro 7.4-2012.04-0ubuntu2.1) 7.4-2012.04
Copyright (C) 2012 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 "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://bugs.launchpad.net/gdb-linaro/>...
Reading symbols from /home/zienon/xwh/segmentation/a.out...(no debugging symbols found)...done.
(gdb)
输入:run
(gdb) run
Starting program: /home/zienon/xwh/segmentation/a.out
Program received signal SIGSEGV, Segmentation fault.
0x00000000004004c4 in test() ()
(gdb)
gdb已经查定位到问题出现在函数test()。
输入:quit
A debugging session is active.
Inferior 1 [process 10895] will be killed.
Quit anyway? (y or n)
输入:y
gdb调试结束
注:要想在程序崩溃之前打印core文件,需要做如下设置
ulimit -c
命令返回为0的话需要输入如下
ulimit -c unlimited
再运行程序。会自动生成core文件
再用gdb -c core进行定位