Linux——使用GDB分析core dump文件

转载于:jiange_zh
原文链接

前言

在编程过程中,我们可能常常遇到程序可以通过编译, 但在运行时出现Segment fault(段错误)。 产生段错误就是访问了错误的内存段。
产生段错误时,并不像编译错误一样会提示到文件的某一行, 而是没有任何信息, 这使得我们的调试变得困难起来,特别是代码量比较大的时候,单步调试很麻烦。这时段错误转储的core文件就派上用场了。

产生core dump

下面我们将通过一个例子来说明core文件的使用。

首先编写一份错误的代码:

#include<iostream>
using namespace std;

void dummy_function()
{
    unsigned char* ptr = 0x00; //试图访问地址0x00
    *ptr = 0x00;
}

int main()
{
    dummy_function();
    return 0;
}

编译运行产生coredump:

$ g++ -g -o test test.cpp
$ ./test
段错误 (核心已转储)

查看core dump

发生core dump之后, 可以用gdb查看core文件的内容, 以定位文件中引发core dump的行,其格式如下:

gdb [exec file] [core file]

gdb ./test test.core

在进入gdb后, 用bt命令查看backtrace以检查发生程序运行到哪里, 来定位core dump的文件->行.

$ gdb ./test core
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright © 2014 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”.
Type “show configuration” for configuration details.
For bug reporting instructions, please see:
http://www.gnu.org/software/gdb/bugs/.
Find the GDB manual and other documentation resources online at:
http://www.gnu.org/software/gdb/documentation/.
For help, type “help”.
Type “apropos word” to search for commands related to “word”…
Reading symbols from ./test…done.
[New LWP 3621]
Core was generated by `./test’.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x0804858d in dummy_function () at test.cpp:14
14 *ptr = 0x00;

(gdb) bt //显示函数调用堆栈,显然是main函数调用dummy_function函数
#0 0x0804858d in dummy_function () at test.cpp:14
#1 0x0804859a in main () at test.cpp:19

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值