GDB Debugging Example

GDB Debugging Example

  • This example demonstrates how you would capture an error that is happening due to an exception raised while dividing by zero.
 GDB Debugging Example

GDB Debugging Example

Sample Code

#include <iostream>
using namespace std;  

int div int(int, int);  
int main() 
   int x = 6, y = 3; 
   cout << divint(x, y); 
   x =3; y = 0; 
   cout << divint(x, y); 
   return 0; 

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

  • To enable debugging, the program must be compiled with the -g option.
    • $g++ -g -o crash

Read Also

We are using g++ compiler because we have used C++ source code.


Floating point exception (core dumped) 

You will find a core file in your current directory.

Now to debug the problem, start gdb debugger at the command prompt:

$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 
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  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  

(gdb) where 
#0  0x08048681 in divint(int, int) (a=3, b=0) at 
#1  0x08048654 in main () at 
# 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  This, in turn, 
# was called from the function main at line 13 of  

(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  

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

  • In this example, it is fairly obvious that the crash occurs because of the attempt to divide an integer by 0.
  • To debug a program 'crash' that has crashed and produced a core file named 'core', type the following at the command line:
    • gdb crash core

Related Searches to GDB Debugging Example

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add to your ad blocking whitelist or disable your adblocking software.