Skip to content
Tutorials Center
My learning

Topics

Lesson 117 of 171 ยท Errors and Debugging

Assertions and Debugging

Find C++ bugs fast - assert and NDEBUG, static_assert, debug logging with std::source_location, library assertions, sanitizers, gdb basics and reading template errors.

Every programmer writes bugs; good programmers find them quickly. In C++ that matters even more than in most languages, because many mistakes don't crash right away. An out-of-bounds write or a dangling reference is undefined behavior: the program may keep running with corrupted data and fail much later, far from the real cause. The winning strategy is to make bugs loud and early: check your assumptions in the code, let the compiler and libraries check more, and use tools that catch memory errors at the exact line where they happen.

This lesson covers that toolbox from the inside out. You'll start with assert and static_assert, which document and check assumptions. Then you'll add useful debug output with std::source_location, switch on the standard library's own checks, meet the sanitizers and a debugger such as gdb, and learn how to read the long compiler errors that templates produce.

assert: check what must be true

assert(condition) from <cassert> checks a condition at run time. If the condition is false, it prints the expression, the file, the line and the function to standard error, then calls std::abort(). Use it for things that can only be false because of a bug: broken preconditions, impossible states, violated invariants.

C++ assert stops the program at the bug

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.

This example fails on purpose. The first call prints average: 5. The second call trips the assertion, and the program stops with a message on standard error that names the file, line, function and expression: main.cpp:7: double average(const std::vector<double>&): Assertion `!values.empty() && "average() needs at least one value"' failed. Because a string literal is always "true", && "message" doesn't change the condition but does put your explanation into the output.

NDEBUG turns assertions off

assert is a macro. When the macro NDEBUG is defined before <cassert> is included, usually with the compiler flag -DNDEBUG in release builds, every assert expands to nothing. That has two consequences:

C++
assert(file.is_open());            // fine: only checks
assert(connect_to_server());       // WRONG: in release builds the call disappears!

bool connected = connect_to_server();
assert(connected);                 // right: the work happens either way
  • Never put side effects inside assert. Release builds would skip the work.
  • Don't use assert for errors that can happen in a correct program, such as a missing file or bad user input. Those need real error handling: exceptions or the tools from Error Handling Without Exceptions.

Our editor compiles without NDEBUG, so assertions are always active here. CMake's default "Release" configuration adds -DNDEBUG; "Debug" doesn't.

C++26 adds contracts: pre(...) and post(...) conditions on function declarations and a contract_assert statement, with build-time control over whether violations are checked, logged or ignored. Compilers are still implementing them, so for now assert remains the standard tool.

static_assert: checks at compile time

static_assert(condition, "message") checks a condition while compiling. If it's false, the build fails with your message. It costs nothing at run time and can't be switched off. Use it to state assumptions about types, sizes and constants that the rest of your code relies on. Since C++17 the message is optional.

C++ Compile-time checks with static_assert

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.

Inside templates, concepts are now usually the better way to restrict types, because they reject a bad call at the call site. static_assert is still perfect for facts about sizes, layouts and constexpr values.

Debug output that tells you where it came from

Printing values is the oldest debugging technique and still one of the most effective. Two habits make it much better:

  • Print to std::cerr (or stderr), not std::cout. Error output is unbuffered, so a message appears immediately even if the program crashes on the next line, and it doesn't mix into the real output you might redirect to a file.
  • Include the location. C++20's std::source_location from <source_location> gives you the file, line and function of the caller when used as a default argument, with no macros needed.
C++ A debug log helper with std::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.

The default argument std::source_location::current() is evaluated at each call site, so every message shows the line of the debug_log call, such as [main.cpp:18 in int find_index(const std::vector<int>&, int)] searching. The debug lines go to stderr and the results to stdout; our editor shows both streams.

For lasting diagnostics in larger programs, use a logging library (spdlog is popular) with log levels, so you can turn detail up or down without editing code.

Let the standard library check itself

By default v[i] on a std::vector doesn't check the index, because checking costs time. But GCC's standard library has a built-in checking mode. Defining the macro _GLIBCXX_ASSERTIONS (normally with -D_GLIBCXX_ASSERTIONS on the command line) turns on cheap precondition checks in operator[], front(), back(), std::optional::operator* and many more. In our editor you can define it at the top of the file, before any #include.

C++ Bounds checks from _GLIBCXX_ASSERTIONS

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.

This example fails on purpose. Without the macro, reading scores[3] is undefined behavior: you might get a garbage total and never notice. With it, the program stops right after adding scores[3] with Assertion '__n < this->size()' failed, pointing straight at the bug. Clang's libc++ and MSVC have similar modes (_LIBCPP_HARDENING_MODE, _ITERATOR_DEBUG_LEVEL). Many projects keep these checks on in debug builds, and some even ship with them.

Sanitizers: catch memory bugs as they happen

Sanitizers are compiler features that add checks to your program while it's built. They're the most important bug-finding tool in modern C++, and they're free with GCC and Clang. Our editor uses a fixed set of flags, so you'll run these on your own machine:

Terminal
# AddressSanitizer + UndefinedBehaviorSanitizer, with debug info and no optimization
g++ -std=c++23 -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer main.cpp -o app
./app
Sanitizer Flag Catches
AddressSanitizer (ASan) -fsanitize=address out-of-bounds reads and writes on heap, stack and globals, use-after-free, double free, leaks
UndefinedBehaviorSanitizer (UBSan) -fsanitize=undefined signed overflow, bad shifts, null dereference, misaligned access, invalid enum values
ThreadSanitizer (TSan) -fsanitize=thread data races between threads (can't be combined with ASan)
MemorySanitizer (MSan, Clang only) -fsanitize=memory reads of uninitialized memory

When ASan finds a problem, it stops the program and prints a report such as ERROR: AddressSanitizer: heap-use-after-free, followed by three stack traces: where the bad access happened, where the memory was freed and where it was allocated. That turns a mysterious crash into a precise answer. The cost is roughly a 2x slowdown and more memory, which is fine for tests. Run your test suite under ASan and UBSan regularly, ideally in continuous integration.

On Windows, MSVC supports AddressSanitizer with /fsanitize=address.

Using a debugger

A debugger lets you pause a running program, step through it line by line, and inspect variables. The common ones are gdb (GNU), lldb (LLVM, the default on macOS), and the debuggers built into Visual Studio, CLion and VS Code. Build with -g (debug information) and preferably -O0 or -Og, so variables aren't optimized away.

A short gdb session looks like this:

TEXT
$ g++ -std=c++23 -g -O0 main.cpp -o app
$ gdb ./app
(gdb) break average           # stop when average() is called
(gdb) run                     # start the program
(gdb) next                    # run the next line, stepping over calls
(gdb) step                    # step into a function call
(gdb) print values.size()     # evaluate an expression
(gdb) info locals             # show all local variables
(gdb) backtrace               # show the call stack (bt for short)
(gdb) watch sum               # stop whenever sum changes
(gdb) continue                # run until the next breakpoint
(gdb) quit

The most valuable single command is backtrace. When a program crashes or an assert fires under the debugger, bt shows exactly which chain of calls led there. lldb uses slightly different syntax (breakpoint set -n average, frame variable), and IDEs put the same features behind clickable breakpoints and variable panels.

C++23 also added std::stacktrace (<stacktrace>) to capture the call stack from inside a program, for example in an error log. GCC requires linking an extra library (-lstdc++exp) for it, so it's not available in our editor.

Reading compiler errors, especially template errors

Compiler errors are debugging too. Simple ones are easy: a missing semicolon, an undeclared name. Template errors are notorious because the mistake is in your code but the error is reported deep inside library code. Run this example; it fails to compile on purpose:

C++ A template error to practice on

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.

GCC prints about thirty lines. Here's how to read them:

  1. Find the first error: line. Here it's error: no match for 'operator-' (operand types are 'std::_List_iterator<int>' and 'std::_List_iterator<int>'). std::sort needs to subtract iterators, and list iterators can't do that.
  2. Find the line in your file. Look for main.cpp and required from here: main.cpp:6:14: required from here. That's the call you need to fix.
  3. Read the "In instantiation of" line to see which template was being built and with which types: std::sort with _RAIter = _List_iterator<int>. The name _RAIter hints that a random-access iterator was expected.
  4. Skip the "candidate" notes at first. They list every overload the compiler tried and rarely help.

The fix is numbers.sort(), since lists have their own sort (see Iterators for why). If you call the C++20 version, std::ranges::sort(numbers), the error is shorter and clearer, because the algorithm is constrained with concepts: it says constraints not satisfied and 'std::random_access_iterator_tag' is not a base of 'std::bidirectional_iterator_tag'. That's one of the big practical wins of concepts.

Other tips that save hours:

  • Fix the first error first. Later errors are often consequences of the first one.
  • Compile with -Wall -Wextra (our editor does) and treat warnings as bugs. Many runtime bugs show up as a warning first.
  • Try another compiler on Compiler Explorer (godbolt.org): Clang's messages sometimes explain the same mistake better.
  • Reduce the problem. Copy the failing code into a tiny program and delete parts until the error is obvious. The same works for runtime bugs.

A debugging workflow

When something goes wrong, work through these steps:

  1. Reproduce it reliably with the smallest possible input.
  2. Read every warning and rebuild with sanitizers and _GLIBCXX_ASSERTIONS.
  3. Check your assumptions with asserts at function entries and after tricky steps.
  4. Narrow down the location with debug output or breakpoints, halving the suspicious region each time.
  5. Fix the cause, not the symptom, then add a test so the bug can't return.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A release build is compiled with -DNDEBUG. What happens to assert(save_file());?

    With NDEBUG, assert expands to nothing. Never put work with side effects inside assert.
  2. 2. When is a static_assert checked?

    static_assert is evaluated by the compiler, costs nothing at run time and can't be disabled by NDEBUG.
  3. 3. void log(std::string_view m, std::source_location loc = std::source_location::current()); is called on line 30. Which line does loc.line() report?

    Default arguments are evaluated where the function is called, which is exactly what makes source_location useful for logging.
  4. 4. Which tool would most directly report a use-after-free, including where the memory was freed?

    ASan instruments every memory access and prints stack traces for the bad access, the free and the original allocation.
  5. 5. A template error is 40 lines long. Where should you look first?

    The first error names the real problem and "required from here" shows which line of your code triggered it. Candidate notes are rarely needed.

Summary

  • assert checks conditions that only a bug can break; it prints the expression and location, then aborts. NDEBUG removes it, so never put side effects inside.
  • static_assert checks types, sizes and constants at compile time, for free.
  • Debug output belongs on std::cerr; std::source_location adds file, line and function without macros.
  • -D_GLIBCXX_ASSERTIONS adds bounds and precondition checks to GCC's standard library.
  • Sanitizers (-fsanitize=address,undefined, thread) catch memory errors, UB and data races at the exact line; run tests under them.
  • Debuggers (gdb, lldb, IDEs) let you break, step, print and backtrace; build with -g.
  • For template errors, read the first error: and the required from here line in your file.

Next: I/O Streams in Depth, where you'll master cin, cout, stream states and manipulators.