aboutsummaryrefslogtreecommitdiffstats
path: root/common/almalloc.cpp
diff options
context:
space:
mode:
authorSven Gothel <[email protected]>2023-05-03 16:17:49 +0200
committerSven Gothel <[email protected]>2023-05-03 16:17:49 +0200
commitec167fd05661a5b02dd406c87081f84a0f8dd77d (patch)
tree9c4669e471c9969bda59265381b18d2d416db060 /common/almalloc.cpp
parent0d14d30808cfe7b9e3413353e3eef8a0f201399a (diff)
parentd3875f333fb6abe2f39d82caca329414871ae53b (diff)
Merge branch 'v1.23.1'
Resolved Conflicts: CMakeLists.txt
Diffstat (limited to 'common/almalloc.cpp')
-rw-r--r--common/almalloc.cpp42
1 files changed, 18 insertions, 24 deletions
diff --git a/common/almalloc.cpp b/common/almalloc.cpp
index 842fb400..ad1dc6be 100644
--- a/common/almalloc.cpp
+++ b/common/almalloc.cpp
@@ -7,61 +7,55 @@
#include <cstddef>
#include <cstdlib>
#include <cstring>
+#include <memory>
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
-#define ALIGNED_ALLOC_AVAILABLE (__STDC_VERSION__ >= 201112L || __cplusplus >= 201703L)
-
void *al_malloc(size_t alignment, size_t size)
{
assert((alignment & (alignment-1)) == 0);
alignment = std::max(alignment, alignof(std::max_align_t));
-#if ALIGNED_ALLOC_AVAILABLE
- size = (size+(alignment-1))&~(alignment-1);
- return aligned_alloc(alignment, size);
-#elif defined(HAVE_POSIX_MEMALIGN)
- void *ret;
+#if defined(HAVE_POSIX_MEMALIGN)
+ void *ret{};
if(posix_memalign(&ret, alignment, size) == 0)
return ret;
return nullptr;
#elif defined(HAVE__ALIGNED_MALLOC)
return _aligned_malloc(size, alignment);
#else
- auto *ret = static_cast<char*>(malloc(size+alignment));
- if(ret != nullptr)
+ size_t total_size{size + alignment-1 + sizeof(void*)};
+ void *base{std::malloc(total_size)};
+ if(base != nullptr)
{
- *(ret++) = 0x00;
- while((reinterpret_cast<uintptr_t>(ret)&(alignment-1)) != 0)
- *(ret++) = 0x55;
+ void *aligned_ptr{static_cast<char*>(base) + sizeof(void*)};
+ total_size -= sizeof(void*);
+
+ std::align(alignment, size, aligned_ptr, total_size);
+ *(static_cast<void**>(aligned_ptr)-1) = base;
+ base = aligned_ptr;
}
- return ret;
+ return base;
#endif
}
void *al_calloc(size_t alignment, size_t size)
{
- void *ret = al_malloc(alignment, size);
- if(ret) memset(ret, 0, size);
+ void *ret{al_malloc(alignment, size)};
+ if(ret) std::memset(ret, 0, size);
return ret;
}
void al_free(void *ptr) noexcept
{
-#if ALIGNED_ALLOC_AVAILABLE || defined(HAVE_POSIX_MEMALIGN)
- free(ptr);
+#if defined(HAVE_POSIX_MEMALIGN)
+ std::free(ptr);
#elif defined(HAVE__ALIGNED_MALLOC)
_aligned_free(ptr);
#else
if(ptr != nullptr)
- {
- auto *finder = static_cast<char*>(ptr);
- do {
- --finder;
- } while(*finder == 0x55);
- free(finder);
- }
+ std::free(*(static_cast<void**>(ptr) - 1));
#endif
}