USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

GDB (GNU Debugger) for Application Debugging

Lesson 21/32 | Study Time: 20 Min

The GNU Debugger (GDB) is a powerful and versatile debugging tool widely used by developers to analyze and troubleshoot programs written in languages such as C and C++.

GDB allows users to observe what happens inside a running program, or examine the state of a program after it crashes.

By enabling features like breakpoints, step execution, variable inspection, and stack trace analysis, GDB helps developers diagnose bugs and understand program behavior in detail. 

Preparing Your Program for Debugging

To use GDB effectively, compile your program with debugging symbols included. This is usually done by adding the -g flag during compilation. Debugging symbols provide GDB with information about variable names, lines of code, and structures.


Example:

bash
gcc -g -o myprogram myprogram.c

This command generates an executable with debug info, enabling source-level debugging.

Starting GDB and Basic Commands

Launch GDB with the program:

bash
gdb ./myprogram


Once inside GDB, the prompt (gdb) indicates readiness for commands.


Basic commands include:


run [args]: starts program execution with optional arguments.

break <line/function>: sets breakpoints to pause execution at specified locations.

next (or n): executes the next line, stepping over function calls.

step (or s): steps into functions to debug inside them.

continue (or c): resumes running until the next breakpoint or program end.

print <variable>: displays a variable’s current value.

info locals: lists local variables in the current frame.

backtrace (or bt): shows the call stack, useful for tracing the function call sequence.

quit: exits GDB.

Advanced Debugging Features


1. Conditional Breakpoints: Break only when conditions are met:

text
break 50 if x > 10


2. Watchpoints: Pause when a variable changes:

text
watch variable_name


3. Core Dumps: Analyze crashes by loading core dump files.

text
gdb ./myprogram corefile


4. Attach to Running Process: Debug live processes by process id (PID).

text
gdb -p <PID>

Viewing Source Code and Assembly


1. list or l: displays source code around the current execution point.

2. disassemble: shows assembly code for low-level debugging.

3. Graphical frontends or TUI mode (Text User Interface) with:

text
gdb -tui ./myprogram

Examining and Modifying Variables


1. Print variable values with print or p.

2. Change variables during execution:

text
set var x=42


3. Inspect memory addresses or complex data structures interactively.

Debugging Workflow Tips