🍗 Wiki

Sanitizers

Sanitizers

Sanitizers in C compilers, including GCC and Clang, enable de by inserting special instruments in code.

It is very useful for developers who want to develop robust programs, and for testers who want to trace the fail cases of fuzzing tests.

1. Famous and Useful Sanitizers

1.1. AddressSanitzer (ASan)

AddressSanitizer can detect general buffer overflows. For example, stack and heap based buffer overflow.

You can add -fsanitize=address option when compiling code with C compilers.

1.2. UndefinedBehaviorSanitizer (UBSan)

UndefinedBehaviorSanitizer can detect logical code errors, like integer overflows/underflows, and null point dereferences.

You can add -fsanitize=undefined option when compiling code with C compilers.

1.3. ThreadSanitizer (TSan)

ThreadSanitizer can detect data race condition errors happened by threads.

You can add -fsanitize=thread option when compiling code with C compilers.

1.4. LeakSanitizer (LeakSan)

LeakSanitizer can detect memory leakage. The most common case is the case of heap chunks(malloc) that are not freed at exit of the program.

int main() {
  void* p = malloc(8);
  p = NULL;
  return 0;
}

It is now integrated to AddressSanitizer, so it is uncommon to use LeakSanitizer alone.

1.5. KernelAddressSanitizer (KASAN)

You can enable kernel-wide address sanitizer in the Linux and the FreeBSD.

  • See how to enable the KASAN on Linux in the Linux document.

  • See how to enable the KASAN on FreeBSD in the FreeBSD document.

1.6. Wconversion

It is not a family member of sanitizers, but it is useful to detect bugs that would be happened by type conversion.

You can add -Wconversion option when compiling code with C compilers.

2. Tips

2.1. How to enable sanitizers to CMake project

Add these two lines to your CMakeLists.txt.

add_link_options(-fsanitize=address)
add_compile_options(-fsanitize=address)