From 1924ba9097d09575a2df8808a7d3a22675699732 Mon Sep 17 00:00:00 2001 From: puqingwu Date: Tue, 9 Dec 2025 15:58:30 +0800 Subject: [PATCH] Fix tcmalloc compatibility issue with aligned_alloc Replace aligned_alloc() with posix_memalign() to fix crashes when using tcmalloc. The issue occurs because aligned_alloc() uses glibc's allocator while tcmalloc replaces free(), causing "invalid pointer" errors when freeing memory. posix_memalign() is more compatible with tcmalloc and other memory allocators, as it properly integrates with the malloc/free interface that tcmalloc intercepts. Changes: - Add #include for posix_memalign() - Replace aligned_alloc() with posix_memalign() in alloc_aligned() - Add proper error handling for posix_memalign() return value This fixes crashes during index construction when InMemDataStore objects are destructed after saving the index. --- include/utils.h | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) 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