From 78022b6e547c088a585bc7c5d5400978498bacf5 Mon Sep 17 00:00:00 2001 From: Giuseppe Ottaviano Date: Thu, 19 Nov 2015 11:39:27 -0800 Subject: [PATCH] Fix usingJEMalloc with Clang Summary: Clang is too clever and in some contexts optimizes away the `malloc`, but we rely on a side-effect. Declaring the variable as static forces it to call `malloc`. We could free the pointer relying on the fact that the lambda is guaranteed to be called only once, but I feel more comfortable just leaking it (LSan won't complain). Reviewed By: philippv Differential Revision: D2674769 fb-gh-sync-id: 1153a3ca226c6b7aa64c453bd61b036dcbf3ffcc --- folly/Malloc.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/folly/Malloc.h b/folly/Malloc.h index 978cd133..d779a063 100644 --- a/folly/Malloc.h +++ b/folly/Malloc.h @@ -159,12 +159,14 @@ inline bool usingJEMalloc() noexcept { uint64_t origAllocated = *counter; - void* ptr = malloc(1); + // Static because otherwise clever compilers will find out that + // the ptr is not used and does not escape the scope, so they will + // just optimize away the malloc. + static void* ptr = malloc(1); if (!ptr) { // wtf, failing to allocate 1 byte return false; } - free(ptr); return (origAllocated != *counter); }(); -- 2.34.1