C++ Debugging
π C++ Debugging
Debugging is the process of finding, understanding, and fixing errors (bugs) in a C++ program.
Good debugging skills save time, effort, and frustration.
πΉ 1. Types of Bugs You Debug
Compile-time bugs β syntax & type errors
Run-time bugs β crashes, segmentation faults
Logical bugs β wrong output, no crash
πΉ 2. Read Compiler Errors Carefully (Most Important)
Always fix the first error first.
Error:
β Fix the missing semicolon first.
πΉ 3. Enable Compiler Warnings
Warnings help catch hidden bugs.
πΉ 4. Use cout for Quick Debugging
β Simple
β Effective for small programs
πΉ 5. Debug with a Debugger (GDB)
Compile with Debug Symbols
Common GDB Commands
| Command | Purpose |
|---|---|
break main | Set breakpoint |
run | Start program |
next | Next line |
step | Step into function |
print x | Print variable |
backtrace | Show call stack |
continue | Resume execution |
πΉ 6. Debugging Runtime Errors
πΈ Segmentation Fault
Common causes:
Dereferencing null pointer
Accessing out-of-bounds array
Using deleted memory
β Fix:
πΉ 7. Debugging Logical Errors
Program runs but output is wrong.
β Trace values step by step
πΉ 8. Use Assertions (assert)
β Stops program if condition fails
β Useful during development
πΉ 9. Check Memory Issues (Advanced)
Common Memory Bugs
Memory leaks
Dangling pointers
Double delete
Tools
Valgrind (Linux)
AddressSanitizer
πΉ 10. Debugging with IDEs
Most IDEs provide:
Breakpoints
Step execution
Variable watch
Call stack view
Popular IDEs:
Visual Studio
Code::Blocks
CLion
VS Code
πΉ 11. Rubber Duck Debugging π¦
Explain your code line by line (even to an object).
Often, the bug reveals itself.
πΉ 12. Best Debugging Practices
β Write small, testable functions
β Test frequently
β Use meaningful variable names
β Avoid large functions
β Use version control (Git)
π Debugging vs Testing
| Debugging | Testing |
|---|---|
| Find bugs | Detect bugs |
| After failure | Before release |
| Manual | Automated |
π Summary
Debugging is a core programming skill
Use compiler warnings & debuggers
Print values and trace logic
Fix memory errors carefully
Practice makes debugging faster
