C++ - Sanitizers & Static Analysis

Overview

Estimated time: 40–60 minutes

Catch bugs early with sanitizers and static analysis. Learn how to enable AddressSanitizer, UBSan, ThreadSanitizer, and run clang-tidy.

Learning Objectives

  • Enable sanitizers in your build for debug/test runs.
  • Run static analyzers and interpret common warnings.

Prerequisites

Sanitizers

# typical compile flags
# clang/gcc: -fsanitize=address,undefined -fno-omit-frame-pointer -O1 -g
# thread sanitizer: -fsanitize=thread

clang-tidy (static analysis)

# run on a file
clang-tidy src/foo.cpp -- -std=c++20 -Iinclude

Common Pitfalls

  • Running sanitizers on Release binaries with aggressive optimizations can reduce report clarity.
  • Ignoring warnings—treat them as quality signals and document exceptions.

Checks for Understanding

  1. What does ASan detect?
  2. How do you run clang-tidy with your project’s compile flags?
Show answers
  1. Memory errors such as use-after-free, buffer overflows.
  2. Provide the same flags after -- so tidy can parse code as your compiler would.

Exercises

  1. Build a small app with ASan/UBSan and deliberately trigger an overflow to see the report.
  2. Run clang-tidy with modernize- checks and fix suggested issues.