GDB - Quick Guide
What is GNU Debugger?
A debugger is a program that runs other programsallowing the user to exercise control over these programsand to examine variables when problems arise.
GNU Debuggerwhich is also called gdb, is the most popular debugger for UNIX systems to debug C and C++ programs.
GNU Debugger helps you in getting information about the following:
If a core dump happenedthen what statement or expression did the program crash on?
If an error occurs while executing a functionwhat line of the program contains the call to that functionand what are the parameters?
What are the values of program variables at a particular point during execution of the program?
What is the result of a particular expression in a program?
How GDB Debugs?
GDB allows you to run the program up to a certain pointthen stop and print out the values of certain variables at that pointor step through the program one line at a time and print out the values of each variable after executing each line.
GDB uses a simple command line interface.
Points to Note
-
Even though GDB can help you in finding out memory leakage related bugsbut it is not a tool to detect memory leakages.
GDB cannot be used for programs that compile with errors and it does not help in fixing those errors.
GDB - Installation
Before you go for installationcheck if you already have gdb installed on your Unix system by issuing the following command:
$gdb -help
If GDB is installedthen it will display all the available options within your GDB. If GDB is not installedthen proceed for a fresh installation.
You can install GDB on your system by following the simple steps discussed below.
step 1: Make sure you have the prerequisites for installing gdb:
An ANSI-compliant C compiler (gcc is recommended - note that gdb can debug codes generated by other compilers)
115 MB of free disk space is required on the partition on which you're going to build gdb.
20 MB of free disk space is required on the partition on which you're going to install gdb.
GNU's decompression programgzip
The make utility - the GNU version is known to work without a problemothers probably do as well.
step 2: Download the gdb source distribution from ftp.gnu.org/gnu/gdb. (We used gdb-6.6.tar.gz for these instructions.) Place the distribution files in your build directory.
step 3: In your build directorydecompress gdb-6.6.tar.gz and extract the source files from the archive. Once the files have finished extractingchange your working directory to the gdb-6.6 directory that was automatically created in your build directory.
$ build> gzip -d gdb-6.6.tar.gz $ build> tar xfv gdb-6.6.tar $ build> cd gdb-6.6
step 4: Run the configure script to configure the source tree for your platform.
$ gdb-6.6> .⁄configure
step 5: Build gdb using the make utility.
$ gdb-6.6> make
step 6: Login as root and install gdb using the following command.
$ gdb-6.6> make install
step 7: If requireddisk space can be reclaimed by deleting the gdb build directory and the archive file after the installation is complete.
$ gdb-6.6> cd .. $ build> rm -r gdb-6.6 $ build> rm gdb-6.6.tar
You now have gdb installed on your system and it is ready to use.
GDB - Debugging Symbols
A Debugging Symbol Table maps instructions in the compiled binary program to their corresponding variablefunctionor line in the source code. This mapping could be something like:
Program instruction ⇒ item nameitem typeoriginal fileline number defined.
Symbol tables may be embedded into the program or stored as a separate file. So if you plan to debug your programthen it is required to create a symbol table which will have the required information to debug the program.
We can infer the following facts about symbol tables:
A symbol table works for a particular version of the program if the program changesa new table must be created.
Debug builds are often larger and slower than retail (non-debug) builds; debug builds contain the symbol table and other ancillary information.
If you wish to debug a binary program you did not compile yourselfyou must get the symbol tables from the author.
To let GDB be able to read all that information line by line from the symbol tablewe need to compile it a bit differently. Normally we compile our programs as:
gcc hello.cc -o hello
Instead of doing thiswe need to compile with the -g flag as shown below:
gcc -g hello.cc -o hello
GDB - Commands
GDB offers a big list of commandshowever the following commands are the ones used most frequently:
b main - Puts a breakpoint at the beginning of the program
b - Puts a breakpoint at the current line
b N - Puts a breakpoint at line N
b +N - Puts a breakpoint N lines down from the current line
b fn - Puts a breakpoint at the beginning of function "fn"
d N - Deletes breakpoint number N
info break - list breakpoints
r - Runs the program until a breakpoint or error
c - Continues running the program until the next breakpoint or error
f - Runs until the current function is finished
s - Runs the next line of the program
s N - Runs the next N lines of the program
n - Like sbut it does not step into functions
u N - Runs until you get N lines in front of the current line
p var - Prints the current value of the variable "var"
bt - Prints a stack trace
u - Goes up a level in the stack
d - Goes down a level in the stack
q - Quits gdb
GDB - Debugging Programs
Getting Started: Starting and Stopping
-
gcc -g myprogram.c
Compiles myprogram.c with the debugging option (-g). You still get an a.outbut it contains debugging information that lets you use variables and function names inside GDBrather than raw memory locations (not fun).
-
gdb a.out
Opens GDB with file a.outbut does not run the program. Youll see a prompt (gdb) - all examples are from this prompt.
r
r arg1 arg2
-
r < file1
Three ways to run a.outloaded previously. You can run it directly (r)pass arguments (r arg1 arg2)or feed in a file. You will usually set breakpoints before running.
help
-
h breakpoints
Lists help topics (help) or gets help on a specific topic (h breakpoints). GDB is well-documented.
q - Quit GDB
Stepping through Code
Stepping lets you trace the path of your programand zero in on the code that is crashing or returning invalid input.
l
l 50
-
l myfunction
Lists 10 lines of source code for current line (l)a specific line (l 50)or for a function (l myfunction).
-
next
Runs the program until next linethen pauses. If the current line is a functionit executes the entire functionthen pauses. next is good for walking through your code quickly.
-
step
Runs the next instructionnot line. If the current instruction is setting a variableit is the same as next. If its a functionit will jump into the functionexecute the first statementthen pause. step is good for diving into the details of your code.
-
finish
Finishes executing the current functionthen pause (also called step out). Useful if you accidentally stepped into a function.
Breakpoints or Watchpoints
Breakpoints play an important role in debugging. They pause (break) a program when it reaches a certain point. You can examine and change variables and resume execution. This is helpful when some input failure occursor inputs are to be tested.
break 45
-
break myfunction
- Sets a breakpoint at line 45or at myfunction. The program will pause when it reaches the breakpoint.
-
watch x == 3
Sets a watchpointwhich pauses the program when a condition changes (when x == 3 changes). Watchpoints are great for certain inputs (myPtr != NULL) without having to break on every function call.
-
continue
Resumes execution after being paused by a breakpoint/watchpoint. The program will continue until it hits the next breakpoint/watchpoint.
-
delete N
- Deletes breakpoint N (breakpoints are numbered when created).
Setting Variables
Viewing and changing variables at runtime is a critical part of debugging. Try providing invalid inputs to functions or running other test cases to find the root cause of problems. Typicallyyou will view/set variables when the program is paused.
-
print x
Prints current value of variable x. Being able to use the original variable names is why the (-g) flag is needed; programs compiled regularly have this information removed.
set x = 3
-
set x = y
- Sets x to a set value (3) or to another variable (y)
call myfunction()
call myotherfunction(x)
-
call strlen(mystring)
Calls user-defined or system functions. This is extremely usefulbut beware of calling buggy functions.
-
display x
Constantly displays the value of variable xwhich is shown after every step or pause. Useful if you are constantly checking for a certain value.
-
undisplay x
- Removes the constant display of a variable displayed by display command.
Backtrace and Changing Frames
A stack is a list of the current function calls - it shows you where you are in the program. A frame stores the details of a single function callsuch as the arguments.
-
bt
Backtraces or prints the current function stack to show where you are in the current program. If main calls function a()which calls b()which calls c()the backtrace is
c <= current location b a main
up
down
Move to the next frame up or down in the function stack. If you are in c, you can move to b or a to examine local variables.
return
- Returns from current function.
Handling Signals
Signals are messages thrown after certain eventssuch as a timer or error. GDB may pause when it encounters a signal; you may wish to ignore them instead.
handle [signalname] [action]
handle SIGUSR1 nostop
handle SIGUSR1 noprint
-
handle SIGUSR1 ignore
Instruct GDB to ignore a certain signal (SIGUSR1) when it occurs. There are varying levels of ignoring.
GDB - Debugging Examples
Go through the following examples to understand the procedure of debugging a program and core dumped.
-
This example demonstrates how you would capture an error that is happening due to an exception raised while dividing by zero.
-
This example demonstrates a program that can dump a core due to non-initialized memory.
Both the programs are written in C++ and generate core dump due to different reasons. After going through these two examplesyou should be in a position to debug your C or C++ programs generating core dumps.
GDB - Summary
After going through this tutorialyou must have gained a good understanding of debugging a C or C++ program using GNU Debugger. Now it should be very easy for you to learn the functionality of other debuggers because they are very similar to GDB. It is highly recommended that you go through other debuggers as well to become familiar with their features.
There are quite a few good debuggers available in the market:
DBX Debugger - This debugger ships along with Sun Solaris and you can get complete information about this debugger using the man page of dbxi.e.man dbx.
DDD Debugger - This is a graphical version of dbx and freely available on Linux. To have a complete detailuse the man page of dddi.e.man ddd.
You can get a comprehensive detail about GNU Debugger from the following link: Debugging with GDB