Skip to content

Instantly share code, notes, and snippets.

@datlife
Last active December 19, 2021 06:49
Embed
What would you like to do?
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).
@AlNotAlbert
Copy link

llvm@8: The x86_64 architecture is required for this software.
Error: llvm@8: An unsatisfied requirement failed this build.
I'm getting this error on M1 Macbook Pro Big sur 11.6

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