Unit 6 of 9 · about 4 hours · measure

Undefined behavior, sanitizers and debugger evidence

Undefined behavior has no promised result, including a crash. Tool evidence helps locate a violated contract without turning one observed output into a language rule.

You'll be able to

  • Identify bounds, lifetime, double-free, uninitialized-read and overflow hazards in C++20 code.
  • Build with warnings, debug symbols, ASan and UBSan, then interpret a report's failing access and lifetime history.
  • Locate a failure in a debugger, repair its root cause and preserve a regression test.

Covers

Out-of-bounds, lifetime, uninitialized access and undefined behaviorCompiler diagnostics, sanitizers and debugger evidence
1

Read

In this order, only the parts listed

0 of 4 done

  1. Undefined behaviorcppreference

    Explanation; UB and optimization: Signed overflow, Access out of bounds and Uninitialized scalar

    Use the C++20 rules. Do not mistake displayed assembly for guaranteed behavior; the C++26 erroneous-behavior distinction is outside this unit.

  2. AddressSanitizerClang AddressSanitizer and UndefinedBehaviorSanitizer

    Introduction; Usage and example_UseAfterFree.cc; Symbolizing the Reports; Additional Checks: Stack Use After Return and Memory leak detection; Limitations

  3. UndefinedBehaviorSanitizerClang AddressSanitizer and UndefinedBehaviorSanitizer

    Introduction; Usage; Available checks, including signed-integer-overflow and the undefined group; Stack traces and report symbolization

    Skip runtime suppression, minimal runtime and newer overflow-behavior attributes.

  4. Debugger backtracesGDB manual: Backtraces

    8.2 Backtraces: bt, -full, frame numbering and optimized-out arguments

    Skip frame filters and backtrace formatting options.

2

Focus on

  • Bounds and lifetime are separate contracts. A stale pointer may still point inside mapped memory; reading it remains invalid.
  • ASan reports memory-access violations with allocation and deallocation stacks. UBSan checks selected undefined operations, including signed overflow; the default undefined group is not a check for every possible defect.
  • Preserve the command, compiler version, input and first report. Repair the invalid lifetime or index calculation rather than suppressing the report.
  • A debugger gives frames and state, not proof that a program has defined behavior. A clean dynamic-tool run covers only executed paths and enabled checks.
Common mistakes · 3
  • ASan and UBSan do not generally detect uninitialized-value use. MemorySanitizer is a separate tool, not part of -fsanitize=address,undefined.
  • A data race is outside ASan/UBSan's usual checks. ThreadSanitizer requires a separate build and cannot be combined with AddressSanitizer.
  • A successful exit is not enough: UBSan can recover after reporting a violation, and an unexecuted bad path remains unchecked.
3

Try it yourself

Closed-book, before checking anything

Run LLVM's example_UseAfterFree.cc with no extra arguments, using clang++ 21.1 -std=c++20 -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer. Preserve the report: the checked run reports 'AddressSanitizer: heap-use-after-free' and 'READ of size 4', with the allocation, delete[] and subsequent read identified. The unsanitized program has undefined behavior and no particular output is guaranteed. Repair it using initialized owned storage that remains alive until after the read, and rerun with the same flags. In a separate program, add argc to numeric_limits<int>::max(): the same diagnostic build reports "signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'" on this Linux x86-64 toolchain. A default recoverable UBSan report need not produce a nonzero exit; use -fno-sanitize-recover=undefined for a failing test target. On a repaired -O0 -g build, run gdb, break main, run and bt to connect the source location to its frame.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.A use-after-free program prints the expected value. Is the read valid?Answer

    No. Its object lifetime ended. Undefined behavior guarantees no particular output, including apparent success.

  2. 2.What evidence distinguishes an invalid index from a freed-buffer access?Answer

    The report's access location and region bounds, plus allocation and deallocation history. Use that history to check the bounds and lifetime independently.

  3. 3.Why can a UBSan-instrumented test exit zero despite a signed-overflow report?Answer

    Many checks recover by default. Configure non-recovery when a violation must fail the test process.

  4. 4.Does a clean ASan/UBSan run prove there are no uninitialized reads or data races?Answer

    No. These tools do not generally cover those defect classes, nor paths that did not execute.

5

Practice

  • AlgoMaster Exercise: Memory Leaks

    Exercises 1 to 5: a single heap id, an early-return path, an exception path with unique_ptr, a partially loaded vector and a linked list

    Build each unfixed starter with clang++ -fsanitize=address -g and keep the LeakSanitizer report before repairing it; the fixed build must report nothing.

You're done when

You explain the failing access from its report, preserve a regression that fails on the seeded defect and passes after repair, and name what the enabled tools still cannot prove.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 7 more in the section
  • cppreferencecppreference community · support

    Consult language lifetime, object model, value categories, memory model, atomics, containers and iterator invalidation while reading or modifying code.

  • Clang AddressSanitizer and UndefinedBehaviorSanitizerLLVM · required

    Compile seeded memory defects with AddressSanitizer and UndefinedBehaviorSanitizer, preserve the reports, repair the root cause and keep regression tests.

  • GDB manual: BacktracesGNU Project · support

    Use section 8.2 for frame numbers, bt, bt -full and optimized-out arguments when inspecting a native failure.

Also in this section

  • AlgoMaster C++AlgoMaster · primary

    Use the sections on compilation, pointers and references, memory, RAII and smart pointers, copy and move, STL containers, templates, errors, concurrency and paired exercises. Skip competitive-programming breadth already covered in Algorithms.

  • C++ Core GuidelinesStandard C++ Foundation community · required

    Use the Philosophy, Interfaces, Resource management, Expressions, Containers and concurrency rule groups to review ownership and safety decisions in the native component.

  • pybind11 documentationpybind11 project · required

    Follow First steps and NumPy support to expose one small native function with explicit shape, dtype, stride, ownership, GIL and exception behavior.

  • CMake tutorialCMake · support

    Use the introductory steps for targets, libraries, testing and install rules. Produce one clean debug build and one optimized build without copied one-off commands.

  • Algorithmica - AoS and SoASergey Slotin · support

    Read the AoS and SoA experiment for a measured case where keeping each record together wins, the counterpart to a single-field scan.

  • `ld.so`: dynamic linker/loaderLinux man-pages project · support

    Read DESCRIPTION, Dynamic string tokens and LD_DEBUG to distinguish link-time symbols from runtime shared-library discovery on Linux.

  • Memory Layout TransformationsIntel · support

    Read Overview and Topics through AOS Form and SOA Form for field-wise access and locality trade-offs. Skip Intel array-notation syntax and the LIBOR example.