C++ · Intermediate level

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

Sanitizers and Undefined Behaviour

Use AddressSanitizer and UndefinedBehaviorSanitizer to catch memory errors and undefined behaviour that tests may miss.

In this lesson you will

  • Build with sanitizers and interpret their reports
  • Recognise common sources of undefined behaviour

Key concepts

undefined behaviourAddressSanitizerUndefinedBehaviorSanitizeruse-after-free

The lesson

Undefined behaviour — reading past an array, using freed memory, signed integer overflow, uninitialised reads — may appear to work today and fail tomorrow on another computer. Sanitizers add run-time checks that detect many of these bugs as they happen.

Build with -fsanitize=address,undefined -g (GCC and Clang) and run the program. When a check fails, the report names the kind of error and shows stack traces for where it happened and, for memory bugs, where the memory was allocated and freed.

Run your tests under sanitizers regularly. They slow the program down, so they are for development and testing, not release builds.

Step by step

  1. Build the seeded program with sanitizers.
  2. Run it and read the use-after-free report.
  3. Fix the dangling reference it reveals.
  4. Find the uninitialised variable using compiler warnings and a sanitizer run.

Practice activity

Find all three seeded bugs in the practical activity and write one sentence per bug on how it was detected.

Expected result: All three bugs are fixed and the program runs cleanly under both sanitizers.

Check your understanding

  1. Why is undefined behaviour dangerous even when a program seems to work?

    Show answer

    It may fail unpredictably on other inputs, compilers or machines.

  2. Which flag enables AddressSanitizer in GCC or Clang?

    Show answer

    -fsanitize=address.

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.