GDB - 除錯示例 1



讓我們編寫一個程式以生成核心轉儲。

#include <iostream>
using namespace std;  

int divint(int, int);  
int main() 
{ 
   int x = 5, y = 2; 
   cout << divint(x, y); 
   
   x =3; y = 0; 
   cout << divint(x, y); 
   
   return 0; 
}  

int divint(int a, int b) 
{ 
   return a / b; 
}   

為了啟用除錯,必須使用 -g 選項來編譯該程式。

$g++ -g crash.cc -o crash 

注意:我們使用 g++ 編譯器,因為我們使用了 C++ 原始碼。

現在,當您在您的 linux 裝置上執行此程式時,它將生成以下結果

Floating point exception (core dumped) 

您將在您的當前目錄中找到一個 core 檔案。

現在,要除錯問題,請在命令提示符下啟動 gdb 偵錯程式

$gdb crash 
# Gdb prints summary information and then the (gdb) prompt
  
(gdb) r 
Program received signal SIGFPE, Arithmetic exception. 
0x08048681 in divint(int, int) (a=3, b=0) at crash.cc:21 
21        return a / b; 

# 'r' runs the program inside the debugger 
# In this case the program crashed and gdb prints out some 
# relevant information.  In particular, it crashed trying 
# to execute line 21 of crash.cc.  The function parameters 
# 'a' and 'b' had values 3 and 0 respectively.  

(gdb) l 
# l is short for 'list'.  Useful for seeing the context of 
# the crash, lists code lines near around 21 of crash.cc  

(gdb) where 
#0  0x08048681 in divint(int, int) (a=3, b=0) at crash.cc:21 
#1  0x08048654 in main () at crash.cc:13 
# Equivalent to 'bt' or backtrace.  Produces what is known 
# as a 'stack trace'.  Read this as follows:  The crash occurred 
# in the function divint at line 21 of crash.cc.  This, in turn, 
# was called from the function main at line 13 of crash.cc  

(gdb) up 
# Move from the default level '0' of the stack trace up one level 
# to level 1.  

(gdb) list 
# list now lists the code lines near line 13 of crash.cc  

(gdb) p x 
# print the value of the local (to main) variable x 

在這個示例中,很明顯崩潰是因為嘗試將一個整數除以 0。

要除錯一個已崩潰並生成了名為“core”的核心檔案的程式“crash”,請在命令列鍵入以下內容

gdb crash core 

由於這基本上相當於啟動 gdb 並鍵入“r”命令,因此現在可以使用上述所有命令來除錯該檔案。

gdb_debugging_examples.htm
廣告