Debugging C Program using gdb
Debugging a C Program Using GDB
Step 1: Compile the C Program with Debugging Option -g
Compile your C program using the -g option.
This allows the compiler to include debugging information.
Example:
(test.c is the sample program to debug)
Step 2: Launch GDB
Start the C debugger (gdb) as shown below:
Step 3: Set Up a Breakpoint Inside the C Program
Syntax:
Example:
This sets a breakpoint at line number 3.
Breakpoints are placed where you suspect errors.
During execution, the debugger stops at the breakpoint and allows you to debug.
Step 4: Execute the C Program in GDB
Run the program using:
(args are optional command-line arguments)
Step 5: Print Variable Values Inside GDB
Syntax:
Example:
Step 6: Continue, Step Over, and Step Into
When the program stops at a breakpoint, you can:
Continue Execution
Runs until the next breakpoint.
Step Over
Executes the next line as a single instruction.
Step Into
Similar to next, but enters functions and executes them line by line.
GDB Command Shortcuts
Miscellaneous GDB Commands
List Source Code
Shows source code in debug mode.
Shows a specific line.
Shows a specific function.
Backtrace (Call Stack)
Prints backtrace of all stack frames (or innermost COUNT frames).
Help
Shows help for a specific topic.
Quit GDB
Exits the debugger.
Demo Video
https://www.youtube.com/watch?v=sCtY--xRUyI
1️⃣ Simple C Program to Debug (test.c)
This program intentionally contains a logical bug.
Expected output:
Actual output (buggy):
2️⃣ Compile with Debug Option
This creates:
3️⃣ Launch GDB
You will see:
4️⃣ List Source Code
Shows the program lines.
5️⃣ Set Breakpoint at main()
Option A — by function name
Option B — by line number
6️⃣ Run the Program
Execution stops at the breakpoint:
7️⃣ Step Through the Program
Execute next line
Keep pressing:
Watch variables:
Output:
8️⃣ Step Into the Function Call
When cursor reaches:
Type:
Now you enter:
9️⃣ Inspect Function Variables
Output:
Step to next line:
Now check:
Output:
🚨 Now you see the problem:
Instead of:
Bug identified!
🔟 Continue Execution
Program finishes.
1️⃣1️⃣ Fix the Bug
Edit program:
Recompile:
Run again:
Correct output:
🧠Quick Debugging Command Summary
| Command | Meaning |
|---|---|
gdb a.out | Start debugger |
l | List source |
break main | Set breakpoint |
run | Run program |
n | Next line |
s | Step into function |
p var | Print variable |
c | Continue |
bt | Backtrace |
quit | Exit |
Comments
Post a Comment