Does realloc of memory allocated by C11 aligned_alloc keep the alignment?
Asked Answered
T

1

13

Consider the following (C11) code:

void *ptr = aligned_alloc(4096, 4096);
... // do something with 'ptr'
ptr = realloc(ptr, 6000);

Since the memory that ptr points to has a 4096-byte alignment from aligned_alloc, will it (read: is it guaranteed to) keep that alignment after a (successful) call to realloc? Or could the memory revert to the default alignment?

Tetrahedral answered 1/12, 2013 at 16:47 Comment(3)
The standard promises no such thing.Laudatory
There is nothing in the standard that says that realloc() shall remember the alignment requirement of the original pointer, therefore the standard does not require that alignment requirements be preserved.Hebraism
Same for posix_memalign: #9078759Middlings
H
8

The alignment is not kept with the pointer. When you call realloc you can only rely on the alignment that realloc guarantees. You'll need to use aligned_alloc to perform any reallocations.

Hydrocele answered 1/12, 2013 at 17:20 Comment(4)
Formally, realloc is no different from malloc+memcpy+free.Confession
@R.. realloc is allowed to optimise that into a grow or shrink and so avoid the memcpyHydrocele
Yes, but that's an optimization that does not violate the formal equivalence. For reasoning about the required behavior with respect to alignment, it's helpful to think as if everything happens as it would in the abstract machine defined by the C standard rather than in terms of optimizations you expect to happen.Confession
@R..: It is different. What you describe is what happens in the worst-case; and you can definitely not assume the worst case always occurs. And even in the abstract machine this isn't what always happens.Woolworth

© 2022 - 2024 — McMap. All rights reserved.