CPSC 213: gdb Tutorial

Purpose

The purpose of gdb is to allow for easy debugging. Although you may argue that you can debug a program easily through visual checks, this is often not the case when there are multiple calls and dependencies. This is especially true when programs are thousands of lines long.

What is gdb?

gdb is a debugging program for code written in C/C++ that is executed through the command line. It works the same way as many other debugging programs. For example, it has a lot of the functionality available in the Eclipse IDE. However, as there isn't a GUI, it is best for you to get acquainted to using commands within the terminal: it follows a simple command-response model of interaction.

How To Start - Compilation

You should now be familiar with compiling C programs with gcc. A typical command that you may use is

gcc -g -o executable_name source.c

where the -o flag specifies a different executable filename than the default a.out. However, to allow the debugger to output additional information for the end user, you need to add the -g flag to allow the compiler to include additional debugging information into the executable.

When you write any code, it is suggested that you keep the -g flag on to allow for easy debugging. The tradeoff is a small increase in compilation time and size of the executable. For the remainder of the CS213 course, please compile with the flag on.

To learn more about other flags for gcc, please see the official online documentation.

How To Start - Executing

Executing gdb is as simple as

gdb executable_name

You need not supply any other arguments. It's easy! You should see a (gdb) prompt once it has loaded your program, indicating that it is ready for use.

gdb's Interface

The interface of gdb works like a usual command-line interface, i.e. you type commands at the prompt and press Enter to execute them. Some useful features to know are:

Running the Debuggee

To run the program, type

run [arguments]

or just

run

if you want to keep the same arguments as the previous run.

If the program executed successfully, it will tell you the program exited normally, else it will give you an error message.

About Error Messages

Error messages tell you the error that occurred and the line where it occurred. They are very useful for narrowing down where exactly the execution faulted. A common error message you will see is SIGSEGV, Segmentation fault.. It simply means that you have tried to access an invalid memory address. This can mean you are accessing an array out of bounds! Google is always helpful to learn more about your error message.

Useful Functions

Control Flow

Shortcuts

These are some shortcuts to help you debug faster.

*some conditions apply.

Advanced Commands


Last modified 2012-10-04 11:07