|
|
Defined in header <cstdlib> | ||
void* aligned_alloc(std::size_t alignment,std::size_t size); | (since C++17) | |
Allocatesize bytes of uninitialized storage whose alignment is specified byalignment (implicitly creating objects in the destination area). Thesize parameter must be an integral multiple ofalignment.
The following functions are required to be thread-safe:
Calls to these functions that allocate or deallocate a particular unit of storage occur in a single total order, and each such deallocation callhappens-before the next allocation (if any) in this order.
Contents |
alignment | - | specifies the alignment. Must be a valid alignment supported by the implementation. |
size | - | number of bytes to allocate. An integral multiple ofalignment. |
On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated withstd::free orstd::realloc.
On failure, returns a null pointer.
Passing asize which is not an integral multiple ofalignment or analignment which is not valid or not supported by the implementation causes the function to fail and return a null pointer (C11, as published, specified undefined behavior in this case, this was corrected byDR460).
As an example of the “supported by the implementation” requirement, POSIX functionposix_memalign
accepts anyalignment that is a power of two and a multiple ofsizeof(void*), and POSIX-based implementations ofaligned_alloc
inherit this requirement.
Fundamental alignments are always supported. Ifalignment is a power of two and not greater thanalignof(std::max_align_t),aligned_alloc
may simply callstd::malloc.
Regularstd::malloc aligns memory suitable for any object type with a fundamental alignment. This function is useful for over-aligned allocations, such as toSSE, cache line, orVM page boundary.
This function is not supported in Microsoft C Runtime library because its implementation ofstd::free isunable to handle aligned allocations of any kind. Instead, MS CRT provides_aligned_malloc
(to be freed with_aligned_free
).
#include <cstdio>#include <cstdlib> int main(){int* p1=static_cast<int*>(std::malloc(10* sizeof*p1));std::printf("default-aligned address: %p\n",static_cast<void*>(p1));std::free(p1); int* p2=static_cast<int*>(std::aligned_alloc(1024,1024));std::printf("1024-byte aligned address: %p\n",static_cast<void*>(p2));std::free(p2);}
Possible output:
default-aligned address: 0x2221c201024-byte aligned address: 0x2222400
(since C++11)(deprecated in C++23) | defines the type suitable for use as uninitialized storage for types of given size (class template)[edit] |
C documentation foraligned_alloc |