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

  1. Compile-time bugs – syntax & type errors

  2. Run-time bugs – crashes, segmentation faults

  3. Logical bugs – wrong output, no crash


πŸ”Ή 2. Read Compiler Errors Carefully (Most Important)

Always fix the first error first.

int main() {
int x = 10
cout << x;
}

Error:

expected ';'

βœ” Fix the missing semicolon first.


πŸ”Ή 3. Enable Compiler Warnings

Warnings help catch hidden bugs.

g++ -Wall -Wextra -pedantic program.cpp

πŸ”Ή 4. Use cout for Quick Debugging

cout << "Value of x: " << x << endl;

βœ” Simple
βœ” Effective for small programs


πŸ”Ή 5. Debug with a Debugger (GDB)

Compile with Debug Symbols

g++ -g program.cpp

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

int *p = nullptr;
cout << *p; // ❌ segfault

βœ” Fix:

if (p != nullptr)
cout << *p;

πŸ”Ή 7. Debugging Logical Errors

Program runs but output is wrong.

int sum = 0;
for (int i = 1; i <= 5; i++)
sum += i;

cout << sum; // expected 15

βœ” Trace values step by step


πŸ”Ή 8. Use Assertions (assert)

#include <cassert>

int divide(int a, int b) {
assert(b != 0);
return a / b;
}

βœ” 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

g++ -fsanitize=address program.cpp

πŸ”Ή 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

You may also like...