GDB

The GNU Debugger (GDB) is a portable debugger that works on many Unix systems and programming languages such as Assembly, C, C++, Rust, and others. GDB offers powerful tools for tracing, examining, and altering the execution of computer programs.

When would you use GDB

Suppose you are trying to run a simple program that compiles correctly but does not produce the expected output. GDB is a debugging tool that helps you track your program’s resources and behavior as it executes.

How to use GDB

To use GDB, compile your program with the GCC compiler’s -g flag to include debug information.

gcc -g <file> -o <program_name>

Once compiled, you can open your program in GDB with:

gdb ./<program_name>

When you open GDB, you will see a command prompt. If the program was compiled correctly, GDB will recognize it as a debug file and allow you to start debugging.

GDB Execution process, starting with the user compiling their file with the -g to load the debug symbols then executing the program as an argument for the gdb command

After loading the program with debug symbols, it can be helpful to visualize your code and see the current line being executed. You can enable this with the command: tui enable

A blank tui enable screen in gdb featuring the code block the user is opening and the empty command line.

When debugging, you may want to examine your program at a specific moment. To do this, set a breakpoint using the break or b command:

break [Line_Number]
break [Function_Name]

Break main and break Line number being used to create a breakpoint in the debugger.

Exiting GDB can be confusing at first, but you can use the quit command or ctrl + d to exit whether the program is running or idle.

quit being used to exit a file when the debugger is still in the command line

GDB has many commands and to learn more we would encourage you to read the GDB Documentation.

Where is GDB not useful?

GDB can struggle with detecting memory issues. For this, another useful tool is Valgrind. When working with memory, inconsistencies and leaks can happen, but running valgrind on a program file can output potential memory leaks.

valgrind [Program_File]

Valgrind is a powerful tool. For more information, see Valgrind’s manual.