Built-in Clang / LLVM shipped by Xcode does not support Leak Santizer (-fsantize=leak
) feature. For example, this code has memory leak:
// File: main.c
#include <stdlib.h>
int main() {
int *array = (int *)malloc(sizeof(int) * 100);
array = NULL; // <--- Memory Leak
return 0;
}
- Compile with clang will throws an exception:
$ which clang
/usr/bin/clang
$ clang -g -fsanitize=leak main.c
clang: error: unsupported option '-fsanitize=leak' for target 'x86_64-apple-darwin18.2.0'
- Install latest Clang/LLVM with Homebrew
brew install llvm@8
- Overwrite the default Clang with latest Clang
echo 'export PATH="/usr/local/opt/llvm/bin:$PATH"'
- Make sure Clang is updated
$ which clang
/usr/local/opt/llvm/bin/clang
clang -g -fsanitize=leak main.c
$ ./a.out
=================================================================
==2895==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 400 byte(s) in 1 object(s) allocated from:
#0 0x107922de6 in wrap_malloc (libclang_rt.lsan_osx_dynamic.dylib:x86_64h+0x7de6)
#1 0x107914f78 in main main.c:4 # <----- It points out the potential cause of memory leak!! :D
#2 0x7fff7cbdced8 in start (libdyld.dylib:x86_64+0x16ed8)
SUMMARY: LeakSanitizer: 400 byte(s) leaked in 1 allocation(s).
Be sure to use the following instead on newer macOS (i.e. ARM macOS):
echo 'export PATH="/opt/homebrew/opt/llvm/bin:$PATH"' >> ~/.zshrc