Skip to content
Advertisement

Is there a linux equivalent of _aligned_realloc

Is there a linux equivalent of _aligned_realloc?

I want to use realloc so I don’t have to memcpy the data every time I resize it. Am I stuck with mmap? I only used mmap once is there a recommended way of implementing memory that will be resized a few times? I’m assuming I can’t mix mmap with aligned_alloc and I would have to do memcpy for the first resize? (or always use mmap)

The realloc below doesn’t always align. I tested under (64bit) linux using gcc and clang

JavaScript

Advertisement

Answer

No, there is neither standard alternative in C++, nor in POSIX standard, nor in the GNU C library.

Here is a proof of concept using only standard functions:

JavaScript

As pointed out in the comments: This has the caveat that in the worst case std::realloc may fail to reuse the allcation and also happens to return an misaligned pointer, then we allocate twice.

We can skip attempting to realloc by just unconditionally allocting, copying and freeing which removes both the worst case of double allocation and the best case of no allocation:

JavaScript

The obvious problem with this is that we have to know the old size which is was not required with the regular reallocation.

By relying on system specific functions, we can keep the optimal case of avoiding allocation and avoid double allocation and also not require knowing the old size:

JavaScript

The helper function used above:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement