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 机器上运行此程序时,它将产生以下结果:

浮点异常(核心转储)

您将在当前目录中找到 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"的核心文件的程序"崩溃",请在命令行中键入以下内容:

gdb crash core

由于这基本上相当于启动 gdb 并键入"r"命令,因此上述所有命令现在都可用于调试该文件。

gdb_debugging_examples.html