22. Debugging with GDB, Valgrind & Compiler Sanitizers
🔴 Difficulty: Advanced | GDB Breakpoints, Backtraces, ASan (-fsanitize=address) & UBSan
📖 Definition
Debugging is the process of diagnosing and resolving software defects (bugs) in C binaries. Modern C debugging combines interactive step-by-step debuggers (GDB - GNU Debugger), compiler instrumentation sanitizers (AddressSanitizer - ASan and UndefinedBehaviorSanitizer - UBSan), and runtime memory checkers (Valgrind).
🎯 Why It Is Used
- Segmentation Fault Diagnosis: Using GDB backtraces (
bt) to pinpoint the exact line number and function call stack where a null pointer or illegal memory access occurred. - Catching Undefined Behavior: Using UBSan (
-fsanitize=undefined) to catch signed integer overflows, null pointer dereferences, and unaligned accesses automatically during test execution.
⚙️ How It Works: Essential GDB Commands
To enable GDB symbol debugging, compile binaries with the -g flag (e.g. gcc -g -Wall main.c -o myprog):
| GDB Command | Shorthand | Action / Purpose |
|---|---|---|
run [args] | r | Starts executable execution with optional arguments. |
break location | b | Sets a breakpoint at function name or line number (e.g. b main.c:25). |
next | n | Executes next source line, stepping OVER function calls. |
step | s | Executes next source line, stepping INTO function calls. |
print expr | p | Evaluates and prints value of a variable/expression (e.g. p *ptr). |
backtrace | bt | Prints current call stack frames from crash location to main(). |
continue | c | Resumes execution until next breakpoint or crash. |
📝 Syntax: Compiler Sanitizer Flags
# 1. Compile with AddressSanitizer (Memory leaks, out-of-bounds, Use-After-Free)
gcc -Wall -Wextra -std=c11 -g -fsanitize=address main.c -o app_asan
# 2. Compile with UndefinedBehaviorSanitizer (Integer overflow, shift out-of-bounds)
gcc -Wall -Wextra -std=c11 -g -fsanitize=undefined main.c -o app_ubsan
# 3. Combine both Sanitizers for Maximum Rigor
gcc -Wall -Wextra -std=c11 -g -fsanitize=address,undefined main.c -o app_sanitizing
💻 Code Walkthrough: Diagnosing Memory Bugs
1. Buggy Code: buggy.c
#include <stdio.h>
#include <stdlib.h>
void trigger_crash(int *p) {
printf("Accessing pointer: %d\n", *p); // CRASH if p == NULL!
}
int main(void) {
int *ptr = NULL;
trigger_crash(ptr); // Triggers Segmentation Fault (Signal 11)
return 0;
}
2. GDB Session Walkthrough
$ gcc -g buggy.c -o buggy
$ gdb ./buggy
(gdb) run
Starting program: ./buggy
Program received signal SIGSEGV, Segmentation fault.
0x0000555555555149 in trigger_crash (p=0x0) at buggy.c:5
5 printf("Accessing pointer: %d\n", *p);
(gdb) bt
#0 0x0000555555555149 in trigger_crash (p=0x0) at buggy.c:5
#1 0x000055555555516e in main () at buggy.c:10
(gdb) p p
$1 = (int *) 0x0
🌼 Intermediate Example: Invariant Checks with assert()
#include <stdio.h>
#include <assert.h>
double calculate_average(const int arr[], size_t count) {
// Runtime assertion verifying preconditions during development
assert(arr != NULL && "Array pointer must not be NULL!");
assert(count > 0 && "Element count must be greater than zero!");
int sum = 0;
for (size_t i = 0; i < count; i++) {
sum += arr[i];
}
return (double)sum / count;
}
int main(void) {
int data[] = {10, 20, 30};
printf("Average: %.2f\n", calculate_average(data, 3));
// Uncommenting below triggers assert() abort failure!
// calculate_average(NULL, 0);
return 0;
}
💻 Expected Terminal Output
Average: 20.00
=== GDB Backtrace Crash Diagnostics ===
Program received signal SIGSEGV, Segmentation fault.
p = (int *) 0x0 (Null pointer dereference identified at line 5)
⚠️ Common Mistakes & Pitfalls
- Forgetting
-gFlag During Compilation: Compiling without-gleaves GDB with no line numbers or symbol names, printing raw hexadecimal addresses instead of source code locations. - Leaving Debug Sanitizers in Release Builds: Shipping binaries built with
-fsanitize=addressto production increases binary size and reduces runtime execution speed.
📌 Important Rules & Limitations
- Always compile with
gcc -gwhen debugging with GDB or Valgrind. - Use
-fsanitize=address,undefinedduring testing to catch memory corruption and undefined behavior automatically.
🌐 Multilingual Explanation: English
Debugging uses GDB for interactive stack backtraces, ASan (-fsanitize=address) for memory corruption, and UBSan for undefined behavior checks. Always compile debug builds with -g.
🌐 Multilingual Explanation: Hindi (Roman Script)
Debugging ke liye gcc -g se compile karke GDB chalayein. Segmentation faults ka exact line number dekhne ke liye GDB mein bt (backtrace) command ka upyog karein. ASan se memory leaks aani out-of-bounds access turant pakde jate hain.
🌐 Multilingual Explanation: Marathi (Roman Script)
Debugging sathi gcc -g waaparun GDB aani AddressSanitizer (ASan) vapartat. Crash zalya nantar line number shodhnayasathi GDB madhye bt vapra.
❓ Practice Questions
- What does the
-gGCC compilation flag do? - In GDB, what is the difference between the
step(s) andnext(n) commands? - What memory errors does AddressSanitizer (
-fsanitize=address) catch at runtime?
🚀 Practical Coding Challenge
Compile a buggy C program with gcc -Wall -Wextra -g -fsanitize=address,undefined, run it to observe ASan error reports, fix the bug, and verify a clean execution.
🧭 Navigation & Breadcrumbs
← Previous: 21. Error Handling | Master Syllabus | Next Module: 23. C Standard Library →