C11 introduces aligned_alloc
which supports specifying an alignment. It's implementation defined which alignments are supported, but on POSIX it should be like posix_memalign(3)
, which supports any power of two that's a multiple of sizeof(void*)
.
Also consider, if regular malloc
suffices. malloc
has an alignment of _Alignof(max_align_t)
for all allocations.
In case, C11 isn't available there is posix_memalign(3)
. In case you are on Windows, there is a _aligned_alloc
starting with MSVC 2015 or use VirtualAlloc
and allocate a page-aligned buffer.
If neither of these works, you will have to roll an own solution on top of malloc
. Get the next aligned address, save the alignment on the two preceding bytes. When calling your free wrapper, get the 2 preceding bytes, subtract them from the pointer and free the result.