The GNU Project Debugger (GDB)
Learn about the GNU Debugger (GDB), which is a powerful debugging tool for C, and learn how to run it and view a stack trace with it.
Debugging is the process of identifying the source of errors or bugs in our code, and analyzing the reasons for it. It can help with fixing code crashes, removing logical mistakes, and making our program more efficient.
What is a symbolic debugger?
A debugger is a program that runs other programs, and provides the ability to control the execution of that program, for example, by stepping through one line at a time, and inspecting variables as our program runs. When our program crashes, and UNIX gives us a vague error message, a debugger helps us figure out where it’s crashing, and (with the assistance of our brain) why it’s crashing.
Why not use printf
?
A quick and easy method of debugging that doesn’t require a separate debugger program, is to sprinkle your code with printf
statements that write to the screen, the values of various variables that you think are relevant and related to a crash (or other error). Some people call this adding “trace code” to your program.
The disadvantages of debugging using trace code are that we may need many printf
statements all over the program, and it becomes a nuisance to put them in, take them out, etc. Moreover, a symbolic debugger can do a lot more stuff than simple trace code. It can:
- halt a program
- allow us to inspect variable values
- jump to an arbitrary line of code
- evaluate expressions
- restart from where we left off
We just get more fine-grained control by using a debugger. Finally, we can use the gdb debugger on a program that has already crashed, without having to restart the program. With that we’ll see the state of the program and its variables, at the time of the crash, allowing us to inspect the values of the variables, the location in the program of the crash, etc.
Compiling a program for GDB
GNU Debugger (GDB) is a debugger that’s widely used by C developers.
To allow GDB to run our program, we must compile our program with a special compiler flag, -g
. Here’s a simple example of a program go.c
that we’ll use to illustrate how GDB is used:
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy