← C++

C++ · 11 / 24

Find memory errors with AddressSanitizer

Reproduce a heap access outside its bounds and verify the repaired version.

  • Large
  • Advanced
  • 90 min

Prerequisites: Classes, references, const and RAII, Headers, CMake and first unit tests

In this tutorial
  1. Define the contract
  2. Separate tools and build
  3. Check observable expectations
  4. Detect an incorrect change
  5. Run the exercise separately
  6. Interpret the verification boundary
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

GCC with C++20 and CMake 3.25 or newer. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-21 on Linux x86_64. verify.py explicitly expects a sanitizer finding from the broken program. A crash alone is insufficient evidence. The corrected program must then finish without that finding.

A crash alone does not prove a particular memory error. The sanitizer must report heap-buffer-overflow for the deliberately broken example. The corrected version uses a range loop and must pass with the same instrumentation.

Package contents and individual files

01Define the contract

AddressSanitizer instruments memory accesses. The deliberately broken program reads past a heap allocation. The corrected version checks the boundary. They are built separately so the negative example cannot be mistaken for a safe template.

main.cpp · cppOpen file
#include <iostream>
#include <stdexcept>
#include <vector>
int main() {
  std::vector<int> readings{10, 20, 30};
  int sum = 0;
  for (int reading : readings)
    sum += reading;
  if (sum != 60)
    throw std::runtime_error("Unexpected sum");
  std::cout << "sum=60\n";
}

Run / check

python3 verify.py

02Separate tools and build

Put all files in a new folder. Read the compiler options and run verify.py. A failed command must propagate its exit code to the caller.

verify.py · pyOpen file
import os, subprocess, sys

flags = [
    "g++",
    "-std=c++20",
    "-g",
    "-O1",
    "-fno-omit-frame-pointer",
    "-fsanitize=address",
    "-pthread",
    "-no-pie",
]
for source, name in [("broken.cpp", "broken"), ("main.cpp", "fixed")]:
    subprocess.run(flags + [source, "-o", name], check=True)
    env = dict(
        os.environ, ASAN_OPTIONS="detect_leaks=0", TSAN_OPTIONS="halt_on_error=1"
    )
    result = subprocess.run(["./" + name], capture_output=True, text=True, env=env)
    if name == "broken":
        expected = "heap-buffer-overflow"
        if not result.returncode or expected not in result.stderr:
            print(result.stderr)
            sys.exit(
                "Sanitizer did not demonstrate the expected defect. Check host support."
            )
        print("Expected sanitizer diagnosis:", expected)
    else:
        if result.returncode:
            print(result.stderr)
            sys.exit(result.returncode)
        print(result.stdout.strip())

03Check observable expectations

verify.py explicitly expects a sanitizer finding from the broken program. A crash alone is insufficient evidence. The corrected program must then finish without that finding.

CMakeLists.txt · cmakeOpen file
cmake_minimum_required(VERSION 3.20)
project(learning LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(lesson main.cpp)
enable_testing()
add_test(NAME behaviour COMMAND lesson)
Expected result

verify.py explicitly expects a sanitizer finding from the broken program. A crash alone is insufficient evidence. The corrected program must then finish without that finding.

04Detect an incorrect change

Change a checked condition or expected result. Verification must now fail. Restore the original version afterwards. A green process alone does not explain which property is protected.

05Run the exercise separately

Add a second test with an empty vector. Its sum must be zero.

06Interpret the verification boundary

An empty collection performs no loop iterations. A new sanitizer run verifies both inputs. A successful run covers only the executed paths.

Expected result

Verification finishes successfully and checks the conditions named in the example.

Your exercise

Add a second test with an empty vector. Its sum must be zero.

Show the solution and explanation

An empty collection performs no loop iterations. A new sanitizer run verifies both inputs. A successful run covers only the executed paths.

solution.cpp · cppOpen file
#include <iostream>
#include <stdexcept>
#include <vector>
int main() {
  std::vector<int> readings{10, 20, 30};
  int sum = 0;
  for (int reading : readings)
    sum += reading;
  if (sum != 60)
    throw std::runtime_error("Unexpected sum");
  std::vector<int> empty;
  int empty_sum = 0;
  for (int value : empty)
    empty_sum += value;
  if (empty_sum != 0)
    throw std::runtime_error("Empty input failed");
  std::cout << "sum=60\n";
}

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.