Using GDB to Find a Run-Time Error

Suppose that you want to execute the program called testerror.cpp given below:

   #include <iostream>
   using std::cout;
   using std::endl;

   void print(int a, int b)
   {
   cout << a/b<< endl;
   }

   int main()
   {
      int x, y;
      x = 20;
      y = 0;
      print(x,y);
      return 0;
   }

If you compile and execute this program using

   g++ testerror.cpp
   a.out

you will get only the following message:

   Arithmetic exception

Nothing in this error message indicates where the problem is. The following shows how to use gdb to find the problem.

   $ g++ -g testerror.cpp
   $ gdb a.out
   GNU gdb 4.18
   Copyright 1998 Free Software Foundation, Inc.
   GDB is free software, covered by the GNU General Public License, and you are
   welcome to change it and/or distribute copies of it under certain conditions.
   Type "show copying" to see the conditions.
   There is absolutely no warranty for GDB. Type "show warranty" for details.
   This GDB was configured as "sparc-sun-solaris2.8"...
   (gdb) run
   Starting program: /home/70/rlancast/debugger/a.out
   Program received signal SIGFPE, Arithmetic exception.
   0x10744 in print (a=20, b=0) at testerror.cpp:7
   7 cout << a/b << endl;
   (gdb) where
   #0 0x10744 in print (a=20, b=0) at testerror.cpp:7
   #1 0x10798 in main () at testerror.cpp:15
   (gdb) list 5, 15
   5 void print(int a, int b)
   6 {
   7 cout << a/b << endl;
   8 }
   9
   10 int main()
   11 {
   12 int x, y;
   13 x = 20;
   14 y = 0;
   15 print(x,y);
   (gdb) quit
   The program is running. Exit anyway? (y or n) y
   $

Note the following about this example:

  • You must compile your program with the -g option to prepare to use the debugger: g++ -g testerror.cpp
  • Start the gdb debugger with the executable version of your program: gdb a.out
  • Type run after the (gdb) prompt to begin execution of the program
  • When the error occurs, gdb tells you the line number that caused the error and also shows the line containing the error.
  • The where command shows the sequence of function calls, starting with the main program, that caused the program to get to the current function.
  • You can use the list command to display lines within the current file of the source program.
  • Use the quit command to leave gdb so that you can fix the source program and try again.

Updated: 12/01/2017 10:43PM