Skip to the task
Layout
Back to classic view

You are looking at lesson 4. Your place is still lesson 5, task 1: Functions.

READTask 2 of 23 · step 2: The debugger

The debugger

A breakpoint, the Debug window, the F7 and F8 steps, and how to look for a bug with the debugger.

When a program compiles but calculates wrongly, the compiler can't help any more. You could add a printf wherever you suspect the bug. Faster is the debugger: it stops the program where you want and shows the values of all the variables.

A breakpoint

Click in the gutter next to a line number: a red dot appears, a breakpoint. Ctrl+F8 does the same.

Then start the program not with ▶ but with 🐞 Debug (Shift+F9). The program runs as usual until it reaches the breakpoint, and stops before that line. The line is highlighted: it hasn't run yet.

The Debug window

The Debug window opens at the bottom:

  • Variables: every variable visible at that moment and its value. CLion also shows the same values in grey in the code itself, at the ends of the lines.
  • Console: the program's output and input. When the program waits in read_int, type the number here.

Stepping

Button Key What it does
Step Over F8 runs the line and stops at the next one
Step Into F7 goes into the function the line calls (e.g. read_int → input.c)
Step Out Shift+F8 finishes the function and goes back to where it was called from
Resume F9 carries on to the next breakpoint
Stop Ctrl+F2 stops the program

Most of the time F8 is enough: line by line, watching how Variables changes.

More tools

  • Watches: in the Variables window click + and type an expression, e.g. (double)sum / count. It is worked out again after every step.
  • Evaluate Expression (Alt+F8): works out any expression once.
  • A conditional breakpoint: right-click the red dot → Condition, e.g. i == 3. The program stops only the third time round the loop.

How to look for a bug

  1. Decide what value should be in a certain place.
  2. Put a breakpoint there and see what it is.
  3. They match: the bug is later, go on with F8. They don't: the bug is earlier.

Extra: the sanitizers on your own computer

Optional. AddressSanitizer and UBSan work only on Linux, so in this course GitHub runs them. If you have WSL with Ubuntu and GCC, CLion can build the project there too: Settings → Build, Execution, Deployment → Toolchains → + → WSL, then in the CMake settings turn on the profile CI: ASan + UBSan (Linux) with that WSL toolchain. You then see sanitizer errors straight away, not only after a push.