Skip to main content
Be Bitwise
C++Security-Focused C++

Static Analysis & Sanitizers

There's a small army of tools for catching C++ bugs before users do. Static analysers read your source and infer trouble. Sanitisers compile checks into your binary and trip alarms at runtime. Wired together, they sweep up the bulk of memory safety and concurrency bugs you'd otherwise ship.

clang-tidy

clang-tidy is the workhorse. Hundreds of checks across correctness, performance, readability, and modernisation, all bundled in:

bash
# Run all checks
clang-tidy -checks='*' file.cpp - -std=c++20
# Run specific categories
clang-tidy -checks='bugprone-*,performance-*,modernize-*' file.cpp
# Fix issues automatically
clang-tidy -checks='modernize-*' -fix file.cpp

Key check categories:

bugprone-*: Finds likely bugs

  • bugprone-use-after-move: Detects use of moved-from objects
  • bugprone-string-literal-with-embedded-nul: Catches hidden nulls in strings
  • bugprone-integer-division: Warns about integer division losing precision

modernize-*: Suggests modern C++ replacements

  • modernize-use-auto: Replace explicit types with auto
  • modernize-use-nullptr: Replace NULL/0 with nullptr
  • modernize-loop-convert: Convert C-style loops to range-for
  • modernize-make-unique: Replace new T with make_unique<T>

performance-*: Finds performance issues

  • performance-unnecessary-copy-initialization: Detects copies that should be references
  • performance-move-const-arg: Warns about moving const objects

.clang-tidy Configuration

Create a .clang-tidy file in your project root:

yaml
Checks: >
bugprone-*,
cert-*,
cppcoreguidelines-*,
modernize-*,
performance-*,
readability-*,
-modernize-use-trailing-return-type,
-readability-magic-numbers
WarningsAsErrors: >
bugprone-use-after-move,
bugprone-dangling-handle
CheckOptions:
- key: readability-identifier-naming.ClassCase
value: CamelCase
- key: readability-identifier-naming.FunctionCase
value: lower_case

AddressSanitizer (ASan)

ASan catches memory errors at the cost of roughly 2x runtime — well worth it during testing:

bash
g++ -fsanitize=address -fno-omit-frame-pointer -g -O1 program.cpp
./a.out

What ASan catches:

  • Heap buffer overflow
  • Stack buffer overflow
  • Global buffer overflow
  • Use-after-free
  • Use-after-return (on by default on Linux with current Clang; elsewhere set ASAN_OPTIONS=detect_stack_use_after_return=1)
  • Double free
  • Memory leaks, via LeakSanitizer, which ASan switches on by default on Linux

Platform matters for that last one. On macOS on Apple silicon, ASan reports that detect_leaks isn't supported and Clang rejects -fsanitize=leak outright. Use Apple's leaks tool (leaks --atExit -- ./a.out) or Instruments there instead.

Key Concept

ASan instruments every load and store and keeps a parallel shadow memory mapping which bytes are live. Touch a byte that's poisoned and the report fires immediately, complete with the access site, the allocation stack, and — for use-after-free — the matching deallocation stack.

UndefinedBehaviorSanitizer (UBSan)

UBSan flags undefined behaviour the compiler is otherwise happy to "optimise" into something terrifying:

bash
g++ -fsanitize=undefined -g program.cpp
./a.out

What UBSan catches:

  • Signed integer overflow
  • Division by zero
  • Null pointer dereference
  • Misaligned memory access
  • Out-of-bounds indexing into arrays whose size the compiler knows (int a[10]), but not into a vector or a heap buffer: that's ASan's job
  • Invalid boolean values
  • Invalid enum values
  • Shift by negative or too-large amount
cpp
// UBSan catches this:
int x = INT_MAX;
int y = x + 1; // runtime error: signed integer overflow

ThreadSanitizer (TSan)

TSan detects data races in multithreaded programs:

bash
g++ -fsanitize=thread -g -O1 program.cpp -pthread
./a.out
cpp
// TSan catches this:
int counter = 0;
void increment() {
for (int i = 0; i < 100000; i++) {
counter++; // Data race!
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
}

The output names both racing accesses with full stack traces. Race bugs go from impossible to tractable.

MemorySanitizer (MSan)

MSan catches reads of uninitialised memory. Clang-only — GCC has nothing equivalent:

bash
clang++ -fsanitize=memory -g program.cpp
./a.out
cpp
int main() {
int x;
if (x > 0) { // MSan: use-of-uninitialized-value
std::cout << "positive\n";
}
}

Combining Sanitizers

Sanitisers don't all play nicely together. The compatibility matrix:

CombinationSupported?
ASan + UBSanYes
ASan + TSanNo
ASan + MSanNo
TSan + UBSanYes

Build matrix to keep them separate:

makefile
# Makefile
CXX = g++
CXXFLAGS = -std=c++20 -Wall -Wextra -g
# Debug with ASan + UBSan
debug-asan:
$(CXX) $(CXXFLAGS) -fsanitize=address,undefined -O1 $(SRC) -o $@
# Debug with TSan
debug-tsan:
$(CXX) $(CXXFLAGS) -fsanitize=thread -O1 $(SRC) -o $@ -pthread
# Debug with MSan (Clang only)
debug-msan:
clang++ $(CXXFLAGS) -fsanitize=memory -O1 $(SRC) -o $@

CI Integration

Wire sanitisers into CI so they run on every commit, not just when someone remembers:

yaml
# GitHub Actions example
jobs:
test-sanitizers:
runs-on: ubuntu-latest
strategy:
matrix:
sanitizer: [address, thread, undefined]
steps:
- uses: actions/checkout@v4
- name: Build with sanitizer
run: |
g++ -std=c++20 -fsanitize=${{ matrix.sanitizer }} \
-g -O1 -o test_${{ matrix.sanitizer }} tests.cpp
- name: Run tests
run: ./test_${{ matrix.sanitizer }}

Hardening Flags and Fuzzing

Sanitisers find bugs in tests; hardening flags limit the damage from the ones you ship. Everything in the C track's Hardening C Programs lesson applies unchanged to g++ and clang++: stack protector, _FORTIFY_SOURCE, PIE, full RELRO. C++ adds one more worth having in release builds: -D_GLIBCXX_ASSERTIONS (libstdc++) or -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST (libc++), which bounds-checks operator[] on the standard containers.

The same lesson covers fuzzing with AFL++ and libFuzzer. Both work on C++ code; libFuzzer's entry point just needs extern "C" so the fuzzer can find it:

cpp
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
parse_message(std::string_view(reinterpret_cast<const char*>(data), size));
return 0;
}

Build it with clang++ -g -fsanitize=fuzzer,address and the fuzzer and ASan hunt together.

Practical Workflow

  1. Development build = ASan + UBSan. Run the tests under it.
  2. Pre-commit, run clang-tidy on whatever you changed.
  3. CI runs the full suite under each sanitiser.
  4. Once a sprint, broaden clang-tidy to its full check set and triage what falls out.
  5. Anything multithreaded gets exercised under TSan, no excuses.

Interpreting Sanitizer Reports

When a sanitiser fires, read top to bottom:

  1. Error type — heap-buffer-overflow, data-race, whatever the label says.
  2. Location — the access that triggered the report.
  3. Allocation site — where the memory came from, for any memory-class bug.
  4. Free site — where it was deallocated, for use-after-free.

The stack traces are your map. Walk them and the lifecycle of the offending memory falls into place.

Treat these tools as part of your build, not optional polish. clang-tidy plus the sanitiser family catches an embarrassingly high fraction of bugs that would otherwise reach users.