C++ · Intermediate level

Intermediate level · Module 5: Builds and Debugging with CMake and GDB · Lesson 2 of 3

Debugging with a Debugger

Use breakpoints, stepping, watches and the call stack to find logic errors quickly.

In this lesson you will

  • Set breakpoints and step through code
  • Inspect variables and the call stack to locate a bug

Key concepts

breakpointstep over / into / outwatch expressioncall stack

The lesson

A debugger runs your program under control. Set a breakpoint where the problem seems to start, run, then step over lines or into function calls while watching variable values change.

When a program crashes, the call stack shows the chain of function calls that led there. Walk up the stack to find the first frame in your own code and inspect its variables.

Debug builds (-g, or CMake's Debug type) keep the information the debugger needs. Optimised release builds may reorder or remove variables, making debugging confusing.

Step by step

  1. Build in Debug mode.
  2. Set a breakpoint in a function with a wrong result.
  3. Step through and watch the variables.
  4. Fix the off-by-one error you find.

Practice activity

Use the debugger to find and fix the off-by-one bug in the provided reorder calculation, recording what you observed.

Expected result: The bug is fixed and the learner can show the variable values that revealed it.

Check your understanding

  1. What does the call stack show?

    Show answer

    The chain of function calls leading to the current point.

  2. Why debug a Debug build rather than a Release build?

    Show answer

    Release optimisation can remove or reorder variables, making the debugger's view misleading.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.