There exist several aligned versions of the venerable malloc()
, e.g.:
#include <stdlib.h>
int posix_memalign(void **memptr, size_t alignment, size_t size);
void *aligned_alloc(size_t alignment, size_t size);
#include <malloc.h>
void *memalign(size_t alignment, size_t size);
(originating in POSIX, glibc and Linux libc respectively). But - I can't seem to find any mention of a version of realloc()
which supports alignment. Has it really never been implemented? It seems pretty trivial to combine the functionality of non-aligned realloc()
with the search for an aligned chunk of memory in the aligned malloc()
variants.
Related:
Does realloc keep the memory alignment of posix_memalign?
It's likely but by no means guaranteed that C++ new and C malloc use the same underlying allocator, in which case realloc could work for both. But formally that's in UB-land. And in practice it's just needlessly risky.
realloc returns a void pointer to the reallocated (and possibly moved) memory block. If there is not enough available memory to expand the block to the given size, the original block is left unchanged, and NULL is returned.
The aligned_alloc function allocates space for an object whose alignment is specified by alignment, whose size is specified by size, and whose value is indeterminate.
DESCRIPTION. The posix_memalign() function shall allocate size bytes aligned on a boundary specified by alignment, and shall return a pointer to the allocated memory in memptr. The value of alignment shall be a power of two multiple of sizeof(void *).
Aligned realloc is only implemented in Microsoft with the _aligned_realloc
function.
There is no POSIX version defined and no implementation in Linux. I never understood why though, because it does not seem so complicated to code in glibc.
I think it's a matter of time before someone implement it considering the advent of wide SIMD instructions.
At the moment, just allocate a new block of aligned memory, copy the content and free the old pointer. This should not slow down your application anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With