The GNU Project Debugger gdb

Debugging is the process of finding out where the bug in your code lies. It can fix crashes, remove any logical mistakes, and make your program more efficient. The gdb is a powerful debugging tool for C. Let's examine some of its features.

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 stepping through one line at a time, and inspecting variables as the program is running. When your program crashes, and UNIX gives you a vague error message, a debugger will help you figure out where it is crashing, and (with the assistance of your brain) why it is 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 you may need many printf() statements all over your 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 you to inspect variable values
  • jump to an arbitrary line of code
  • evaluate expressions
  • restart from where you left off

You just get more fine-grained control by using a debugger. Finally, you can use the gdb debugger on a program that has already crashed, without having to re-start the program (you will see the state of the program, and its variables, at the time of the crash, allowing you to inspect the values of the variables, the location in the program of the crash, etc).

Compiling your program for gdb

To allow gdb to run your program, you must compile your program with a special compiler flag, -g. Here is a simple example of a program we will use to illustrate the gdb debugger go.c:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy