1. 程式人生 > 其它 >Linux——使用GDB分析core dump檔案

Linux——使用GDB分析core dump檔案

技術標籤:Linux

轉載於: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