Back to C++
2026-02-086 min read

Debug Reference (C++)

Learn Debug Reference (C++) step by step with clear examples and exercises.

Why This Matters

Debugging is an indispensable skill for every C++ programmer as it enables the identification and resolution of errors in your code. In real-world scenarios, debugging can save time, prevent frustration, and ensure the reliability of your applications. During interviews, demonstrating proficiency in debugging showcases your problem-solving abilities and attention to detail.

Prerequisites

Before diving into C++ debugging, it's essential to have a good understanding of:

  1. Basic C++ syntax and control structures (loops, conditionals)
  2. Data structures like arrays and linked lists
  3. Functions and function overloading
  4. Object-oriented programming concepts (classes, inheritance, polymorphism)
  5. Standard Template Library (STL) containers and algorithms
  6. Understanding of compilers and the compilation process in C++
  7. Familiarity with the command line interface and basic file management
  8. Knowledge of common C++ libraries such as ` and `
  9. Basic understanding of pointers, references, and memory allocation in C++
  10. Understanding of conditional compilation (preprocessor directives)

Core Concept

In C++, debugging is primarily done using the std::cout statement for outputting variables' values during runtime, and tools like Visual Studio Code or gdb for stepping through your code line by line. Additionally, IDEs like CLion offer integrated debugging features that make the process more intuitive.

Debugging with std::cout

To print the value of a variable during runtime, simply include the std::cout statement followed by the variable name within the scope of your program. For example:

#include <iostream>

int main() {
int x = 5;
std::cout << "The value of x is: " << x << std::endl;
return 0;
}

In this example, the output will be "The value of x is: 5".

Debugging with IDEs and gdb

Integrated Development Environments (IDEs) like Visual Studio Code offer built-in debugging features that allow you to step through your code line by line, inspect variables' values, and set breakpoints. To use these features, you need to compile your C++ program with the -g flag, which generates debug information:

g++ -g main.cpp -o main

Once compiled, you can start the debugger and set breakpoints at specific lines:

gdb ./main
(gdb) break 10
(gdb) run

Now, when the program reaches line 10 (the breakpoint), it will pause, allowing you to inspect variables' values and continue executing the code.

Using IDEs for Debugging

IDEs like Visual Studio Code or CLion provide a more user-friendly debugging experience. To start debugging in Visual Studio Code, set breakpoints by clicking on the left gutter next to the line number, then click the "Start Debugging" button (or press F5). The IDE will automatically compile and run your program with the -g flag, allowing you to inspect variables' values during runtime.

Worked Example

Let's consider a simple example of a function that calculates the factorial of a given number:

#include <iostream>
using namespace std;

long long factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}

int main() {
int num = 5;
cout << "Factorial of " << num << ": " << factorial(num) << endl;
return 0;
}

However, this code has a mistake: the function will not work correctly for negative numbers. To debug it, we can add a cout statement inside the function to check the value of n at each recursive call:

#include <iostream>
using namespace std;

long long factorial(int n) {
cout << "Calculating factorial for " << n << ".\n";
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}

int main() {
int num = 5;
cout << "Factorial of " << num << ": ";
cout << factorial(num) << endl;
return 0;
}

Now, when we run the program with a negative number, we can see that it enters an infinite loop:

Calculating factorial for -2.
Calculating factorial for -1.
Calculating factorial for -2.
...

This output indicates that our function has a mistake, and we should fix the base case to handle negative numbers properly.

Common Mistakes

1. Forgetting semicolons

In C++, every statement must be terminated with a semicolon. Failing to do so can lead to syntax errors:

int x = 5;
printf(x); // Syntax error: missing ';' before ')'

2. Incorrect variable initialization

Initializing variables incorrectly can cause unexpected behavior or runtime errors:

int arr[3] = {1, 2}; // Array size is 3, but only two elements are initialized

3. Off-by-one errors

Off-by-one errors occur when you make a mistake in the bounds of loops or arrays:

for (int i = 0; i <= 3; i++) { // Should be i < 3
cout << arr[i] << endl;
}

4. Uninitialized variables

Using uninitialized variables can lead to undefined behavior:

int x;
cout << x << endl; // Outputs garbage value

5. Incorrect use of pointers and memory allocation

Misuse of pointers and dynamic memory allocation can cause segmentation faults or memory leaks:

int *ptr = new int[10]; // Allocate an array of 10 integers on the heap
delete[] ptr; // Forgetting to deallocate memory can lead to a memory leak

Practice Questions

  1. Write a function that finds the maximum element in an array using std::cout.
  2. Debug the following code and find the mistake:
#include <iostream>
using namespace std;

int main() {
int arr[] = {1, 2, 3};
for (int i = 0; i <= 3; i++) { // Should be i < 3
cout << arr[i] << endl;
}
return 0;
}
  1. Write a function that calculates the sum of all even numbers in an array using std::cout.
  2. Debug the following code and find the mistake:
#include <iostream>
using namespace std;

int main() {
int x = 5;
cout << factorial(x) << endl; // Calling the function without defining it first
return 0;
}

FAQ

Q: What is a debugger, and how does it help me?

A: A debugger is a tool that allows you to step through your code line by line during runtime, inspect variables' values, and set breakpoints. This helps identify and fix errors in your code more easily.

Q: How can I use std::cout for debugging my C++ program?

A: By including std::cout statements at specific points within your code, you can print the values of variables during runtime to better understand the flow of execution and identify potential issues.

Q: What is the difference between a compiler and a debugger?

A: A compiler translates your source code into machine-readable format (object files or executables), while a debugger helps you analyze and debug the compiled program during runtime.

Q: How can I use gdb for debugging my C++ program?

A: To use gdb, first compile your program with the -g flag to generate debug information. Then, start the debugger and load your program, followed by setting breakpoints and inspecting variables as needed.

Q: What is an off-by-one error, and how can I avoid it?

A: An off-by-one error occurs when you make a mistake in the bounds of loops or arrays. To avoid off-by-one errors, always ensure that loop indices are within the correct range and that array indices start from 0 instead of 1.

Q: How can I use Visual Studio Code for debugging my C++ program?

A: To start debugging in Visual Studio Code, set breakpoints by clicking on the left gutter next to the line number, then click the "Start Debugging" button (or press F5). The IDE will automatically compile and run your program with the -g flag, allowing you to inspect variables' values during runtime.

Q: How can I use CLion for debugging my C++ program?

A: To start debugging in CLion, set breakpoints by clicking on the left gutter next to the line number, then click the "Debug" button (or press Shift+F9). The IDE will automatically compile and run your program with the -g flag, allowing you to inspect variables' values during runtime.

Debug Reference (C++) | C++ | XQA Learn