Search code examples
cmemory-managementalignmentmallocrealloc

Is there really no version of realloc() supporting alignment?


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?


Solution

  • 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.