diff --git a/include/utils.h b/include/utils.h index d3af5c3a9..1df3b169d 100644 --- a/include/utils.h +++ b/include/utils.h @@ -1,9 +1,10 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include +#include // for posix_memalign #include "common_includes.h" @@ -259,7 +260,15 @@ inline void alloc_aligned(void **ptr, size_t size, size_t align) if (IS_ALIGNED(size, align) == 0) report_misalignment_of_requested_size(align); #ifndef _WINDOWS - *ptr = ::aligned_alloc(align, size); + // Use posix_memalign instead of aligned_alloc for tcmalloc compatibility. + // posix_memalign is more compatible with tcmalloc and avoids "invalid pointer" errors + // when freeing memory allocated with aligned_alloc and freed with tcmalloc's free(). + int ret = posix_memalign(ptr, align, size); + if (ret != 0) + { + *ptr = nullptr; + report_memory_allocation_failure(); + } #else *ptr = ::_aligned_malloc(size, align); // note the swapped arguments! #endif