How to use clang's LeakSanitizer on MacOS?

2.8k views Asked by At

I'm macOS Big Sur. AFAIK, Valgrind doesn't support this OS yet. At least I've tried this.

After some Googling, I switched to LeakSanitizier and tested this C code:

#include <stdlib.h>
void *p;
int main() {
  p = malloc(7);
  p = 0; // The memory is leaked here.
  return 0;
}

This post pointed that clang shipped with macOS doesn't have -fsanitize=address support enabled. So I installed clang from homebrew:

/usr/local/opt/llvm/bin/clang --version
clang version 11.0.0
Target: x86_64-apple-darwin20.1.0
Thread model: posix
InstalledDir: /usr/local/opt/llvm/bin

OK, let's try it:

Ancalagon:Codes anta40$ /usr/local/opt/llvm/bin/clang -g -fsanitize=address leak1.c -o leak1
Ancalagon:Codes anta40$ ./leak1
Ancalagon:Codes anta40$

Nothing happens. Perhaps try llvm-symbolizer

Ancalagon:Codes anta40$ /usr/local/opt/llvm/bin/llvm-symbolizer ./leak1
./leak1

Same result. Perhaps I'm missing something here?

1

There are 1 answers

1
gbudau On BEST ANSWER

To enable LeakSanitizer set ASAN_OPTIONS=detect_leaks=1 or use -fsanitize=leak flag.

Also, according to this, if using the clang version 11.0 and Xcode version 11.3, use clang with -mlinker-version=450 flag to avoid a linker error.

Example:

$ /usr/local/opt/llvm/bin/clang -g -fsanitize=address leak1.c -o leak1
$ ASAN_OPTIONS=detect_leaks=1 ./leak1

or

$ /usr/local/opt/llvm/bin/clang -g -fsanitize=leak leak1.c -o leak1
$ ./leak1