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:
# Run all checksclang-tidy -checks='*' file.cpp - -std=c++20
# Run specific categoriesclang-tidy -checks='bugprone-*,performance-*,modernize-*' file.cpp
# Fix issues automaticallyclang-tidy -checks='modernize-*' -fix file.cppKey check categories:
bugprone-*: Finds likely bugs
bugprone-use-after-move: Detects use of moved-from objectsbugprone-string-literal-with-embedded-nul: Catches hidden nulls in stringsbugprone-integer-division: Warns about integer division losing precision
modernize-*: Suggests modern C++ replacements
modernize-use-auto: Replace explicit types with automodernize-use-nullptr: Replace NULL/0 with nullptrmodernize-loop-convert: Convert C-style loops to range-formodernize-make-unique: Replacenew Twithmake_unique<T>
performance-*: Finds performance issues
performance-unnecessary-copy-initialization: Detects copies that should be referencesperformance-move-const-arg: Warns about moving const objects
.clang-tidy Configuration
Create a .clang-tidy file in your project root:
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_caseAddressSanitizer (ASan)
ASan catches memory errors at the cost of roughly 2x runtime — well worth it during testing:
g++ -fsanitize=address -fno-omit-frame-pointer -g -O1 program.cpp./a.outWhat 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.
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:
g++ -fsanitize=undefined -g program.cpp./a.outWhat 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 avectoror a heap buffer: that's ASan's job - Invalid boolean values
- Invalid enum values
- Shift by negative or too-large amount
// UBSan catches this:int x = INT_MAX;int y = x + 1; // runtime error: signed integer overflowThreadSanitizer (TSan)
TSan detects data races in multithreaded programs:
g++ -fsanitize=thread -g -O1 program.cpp -pthread./a.out// 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:
clang++ -fsanitize=memory -g program.cpp./a.outint 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:
| Combination | Supported? |
|---|---|
| ASan + UBSan | Yes |
| ASan + TSan | No |
| ASan + MSan | No |
| TSan + UBSan | Yes |
Build matrix to keep them separate:
# MakefileCXX = g++CXXFLAGS = -std=c++20 -Wall -Wextra -g
# Debug with ASan + UBSandebug-asan: $(CXX) $(CXXFLAGS) -fsanitize=address,undefined -O1 $(SRC) -o $@
# Debug with TSandebug-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:
# GitHub Actions examplejobs: 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:
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
- Development build = ASan + UBSan. Run the tests under it.
- Pre-commit, run clang-tidy on whatever you changed.
- CI runs the full suite under each sanitiser.
- Once a sprint, broaden clang-tidy to its full check set and triage what falls out.
- Anything multithreaded gets exercised under TSan, no excuses.
Interpreting Sanitizer Reports
When a sanitiser fires, read top to bottom:
- Error type —
heap-buffer-overflow,data-race, whatever the label says. - Location — the access that triggered the report.
- Allocation site — where the memory came from, for any memory-class bug.
- 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.