Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Preprocessor, Tools and Concepts

Debugging C++ with gdb, assert and logging

Practical C++ debugging: build with symbols, use gdb breakpoints and watchpoints, read backtraces and core dumps, and add assert and source_location checks.

Debugging means finding why a program does something other than what you meant. In C++ you have three kinds of tools, and good programmers combine them: checks inside the code (assert, static_assert, logging), a debugger such as gdb, lldb or the Visual Studio debugger, and analysis tools such as sanitizers.

A debugger lets you stop a running program, look at variables, and step line by line. It needs debug symbols, which map machine code back to your source. Without -g, you see addresses and no variable names.

Terminal
g++ -std=c++23 -g -O0 main.cpp -o app       # symbols, no optimization
gdb ./app

The gdb sessions on this page are read-only, because our runner has no interactive terminal. The live examples use checks you put in the code, which work everywhere.

Try it

C++ A check macro with source_location

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ static_assert, assert and a trace helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A gdb session

Compile with -g -O0, then:

TEXT
$ gdb ./app
(gdb) break divide            # stop when divide() is called
(gdb) run                     # start the program
(gdb) next                    # execute one line, stepping over calls
(gdb) step                    # execute one line, stepping into calls
(gdb) print b                 # show a variable (also: print v.size(), print *ptr)
(gdb) watch total             # stop whenever total changes
(gdb) backtrace               # the chain of calls that led here
(gdb) frame 1                 # select a caller to inspect its variables
(gdb) continue                # run until the next breakpoint
(gdb) quit

Useful extras: break file.cpp:42, break foo if x > 10, tbreak (one-time breakpoint), info locals, display x (print after each stop), finish (run until the current function returns), and catch throw (stop whenever an exception is thrown).

Task gdb lldb Visual Studio
Set a breakpoint break f b f F9
Step over / into next / step n / s F10 / F11
Continue continue c F5
Show a variable print x p x Watch window
Backtrace bt bt Call Stack window

Core dumps and crashes

When a program crashes (segmentation fault, abort), the system can save its memory in a core file. Load it with gdb ./app core and run backtrace to see where it died. On Linux, enable it with ulimit -c unlimited. A release build with -g still has useful symbols, and you can strip them for shipping while keeping a separate copy for debugging crashes.

Usage notes

  • Debug with -O0 or -Og. At -O2 variables vanish ("optimized out"), lines jump around and functions are inlined.
  • assert is for impossible conditions, not for bad user input. It aborts with the expression, file and line, and it is compiled out with -DNDEBUG, so it must not contain side effects.
  • Prefer static_assert whenever the condition is known at compile time (sizes, constants, type traits).
  • Print to std::cerr while debugging. It is unbuffered, so its lines appear even if the program crashes right afterwards. Text sitting in std::cout's buffer can be lost in a crash.
  • Print by value, not by hope. Logging the inputs of a failing function often finds a bug faster than stepping through 1,000 iterations.
  • Use watchpoints for "who changed this?" problems, especially with data corrupted by a wild pointer.
  • Reproduce first. Reduce the program until the bug remains in a few lines. That is half of fixing it.
  • Run sanitizers before the debugger when a crash looks like memory corruption: they usually name the faulty line directly (see Sanitizers).
  • C++23 std::stacktrace can print a call chain from inside the program; with GCC 15 it needs an extra library (-lstdc++exp), so it is read-only on our runner (see stacktrace).