Skip to content

Commit 7babf77

Browse files
authored
Merge pull request #461 from serge-sans-paille/feature/portable-aligned-allocator
Improve aligned allocator implementation
2 parents e845404 + 7a4fc55 commit 7babf77

File tree

2 files changed

+16
-16
lines changed

2 files changed

+16
-16
lines changed

include/xsimd/config/xsimd_align.hpp

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,8 @@
5757
#elif XSIMD_ARM_INSTR_SET >= XSIMD_ARM7_NEON_VERSION
5858
#define XSIMD_DEFAULT_ALIGNMENT 16
5959
#else
60-
// some versions of gcc do nos handle alignment set ot 0
61-
// see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69089
62-
#if __GNUC__ < 7
63-
#define XSIMD_DEFAULT_ALIGNMENT 8
64-
#else
65-
#define XSIMD_DEFAULT_ALIGNMENT 0
66-
#endif
60+
// Set the default to the requirements of posix_memalign
61+
#define XSIMD_DEFAULT_ALIGNMENT sizeof(void*)
6762
#endif
6863

6964
#endif

include/xsimd/memory/xsimd_aligned_allocator.hpp

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -281,22 +281,27 @@ namespace xsimd
281281
{
282282
inline void* xaligned_malloc(size_t size, size_t alignment)
283283
{
284-
void* res = 0;
285-
void* ptr = malloc(size + alignment);
286-
if (ptr != 0 && alignment != 0)
284+
assert(((alignment & (alignment - 1)) == 0) && "alignment must be a power of two");
285+
assert((alignment >= sizeof(void*)) && "alignment must be at least the size of a pointer");
286+
void* res = nullptr;
287+
#ifdef _WIN32
288+
res = _aligned_malloc(size, alignment);
289+
#else
290+
if(posix_memalign(&res, alignment, size) != 0)
287291
{
288-
res = reinterpret_cast<void*>(
289-
(reinterpret_cast<size_t>(ptr) & ~(size_t(alignment - 1))) +
290-
alignment);
291-
*(reinterpret_cast<void**>(res) - 1) = ptr;
292+
res = nullptr;
292293
}
294+
#endif
293295
return res;
294296
}
295297

296298
inline void xaligned_free(void* ptr)
297299
{
298-
if (ptr != 0)
299-
free(*(reinterpret_cast<void**>(ptr) - 1));
300+
#ifdef _WIN32
301+
_aligned_free(ptr);
302+
#else
303+
free(ptr);
304+
#endif
300305
}
301306
}
302307

0 commit comments

Comments
 (0)