Skip to content

Commit 78058de

Browse files
committed
address mismatching new/free
1 parent 3edc056 commit 78058de

1 file changed

Lines changed: 12 additions & 3 deletions

File tree

src/common.h

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,17 +34,26 @@
3434

3535
/**
3636
* new_huge - Allocate and construct N objects of type T on 2MB aligned memory.
37-
* Falls back to standard new[] if alignment fails or on other platforms.
37+
* Falls back to standard allocation if alignment fails or on other platforms.
3838
*/
3939
template <typename T> inline T* new_huge(size_t n) {
4040
if (n == 0)
4141
return nullptr;
4242
size_t size = n * sizeof(T);
4343
#ifdef __linux__
44+
// Use nullptr sentinel: posix_memalign leaves ptr unchanged on failure,
45+
// so we can detect fallback to new[] in delete_huge.
4446
void* ptr = nullptr;
45-
// Align to 2MB for Huge Pages
4647
if (posix_memalign(&ptr, 2 * 1024 * 1024, size) != 0) {
47-
return new T[n];
48+
ptr = malloc(size);
49+
if (!ptr) return nullptr;
50+
T* tptr = static_cast<T*>(ptr);
51+
if constexpr (!std::is_trivially_default_constructible_v<T>) {
52+
for (size_t i = 0; i < n; ++i) {
53+
new (&tptr[i]) T();
54+
}
55+
}
56+
return tptr;
4857
}
4958
madvise(ptr, size, MADV_HUGEPAGE);
5059
T* tptr = static_cast<T*>(ptr);

0 commit comments

Comments
 (0)