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.
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.
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.
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.
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:
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.
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.
These are some shortcuts to help you debug faster.