GDB - Debugging Beispiel1



Lassen Sie uns ein Programm schreiben, um einen Core-Dump erzeugen.

#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; 
}   

Um das Debugging zu aktivieren, muss das Programm mit der Option -g kompiliert werden.

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

Hinweis: Wir sind verwenden g ++ Compiler, weil wir haben verwendet C ++ Quellcode.

Wenn Sie laufen dieses Programm auf Ihrem Linux-Rechner, es wird erzeugen das folgende Ergebnis:

Floating point exception (core dumped) 

Sie werden ein Core Datei im Ihren aktuellen Verzeichnis finden.

Nun das Problem zu debuggen, starten gdb-Debugger bei der Eingabeaufforderung:

$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 

In diesem Beispiel ist es ziemlich offensichtlich, dass die Crash tritt wegen der Versuch, eine ganze Zahl durch 0 teilen.

Um ein Programm "Crash", die abgestürzt und eine Kerndatei namens "Kern" produziert hat debuggen, geben Sie Folgendes in der Befehlszeile:

gdb crash core 

Da dies meist entspricht dem Starten von gdb und Typisierung den Befehl 'r', könnte alle Befehle über nun verwendet, um die Datei zu debuggen.

gdb_debugging_examples.htm
Advertisements