Skip to content

Instantly share code, notes, and snippets.

@datlife
Last active July 21, 2024 02:56
Show Gist options
  • Save datlife/c754535f18b422f6b8d59028c7f31bac to your computer and use it in GitHub Desktop.
Save datlife/c754535f18b422f6b8d59028c7f31bac to your computer and use it in GitHub Desktop.
Build LLVM / Clang on MacOS

Build LLVM / Clang on MacOS

Problem

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'

The Fix:

  • 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

Result:

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).
@kcoul
Copy link

kcoul commented May 23, 2024

Be sure to use the following instead on newer macOS (i.e. ARM macOS):

echo 'export PATH="/opt/homebrew/opt/llvm/bin:$PATH"' >> ~/.zshrc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment