Skip to main content

Sanitizers

info

Besides UndefinedBehaviorSanitizer, multiple sanitizers cannot be used at the same time.

Sanitizers is a Google project that is part of both Clang and GCC. It encompasses multiple tools that can help you detect and fix hard to find bugs.

It works by adding extra instructions at compile time and a runtime library. It will require you to re-compile your project, but it can find more bugs than tools such as Valgrind and has a lower performance impact on your program.

More sanitizers, such as MemorySanitizer, are available but not covered here as they are not macOS compatible.

AddressSanitizer​

AddressSanitizer can detect various memory errors, such as:

  • Out-of-bounds accesses to heap, stack and global
  • Use-after-free
  • Use-after-scope
  • Double-free, invalid free

You can enable it with the -fsanitize=address flag.

It is also recommended to add the -fno-omit-frame-pointer and -fno-optimize-sibling-calls flags to get more detailed stack traces.

Example​

LeakSanitizer​

info

LeakSanitizer does not work with the LLVM shipped by Apple, you will have to install a newer version with Homebrew.

LeakSanitizer will show you memory leaks. It is included in AdressSanitizer and enabled by default on Linux, on macOS you will need to enable it explicitly.

You can toggle it by changing the value of detect_leaks to 0 to disable it or 1 to enable it , in the ASAN_OPTIONS variable of your environment.

$ export ASAN_OPTIONS=detect_leaks=1
$ export ASAN_OPTIONS=detect_leaks=0

You can also use the -fsanitize=leak flag to use it as a standalone.

Example​

UndefinedBehaviorSanitizer​

UndefinedBehaviorSanitizer will show you bugs such as:

  • Array subscript out of bounds
  • Dereferencing misaligned or null pointers
  • Signed integer overflow

You can find the list of all checks in the documentation

You can enable it with the -fsanitize=undefined flag.

It is the only sanitizer that can be used with other sanitizers. You can do it by separating them with a comma -fsanitize=address,undefined.

Example​

ThreadSanitizer​

ThreadSanitizer will detect data races in your program.

You can enable it with the -fsanitize=thread flag.

Example​

Resources​