Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 993
einpoklum Avatar asked Aug 04 '17 09:08

einpoklum


People also ask

Can realloc be used with new?

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.

What will happen in case realloc function fails in locating additional memory block?

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.

What is aligned Alloc?

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.

What is Posix_memalign?

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 *).


1 Answers

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.

like image 189
yakoudbz Avatar answered Sep 21 '22 08:09

yakoudbz