[C++] Memory: std::aligned_alloc
Define
aligned_alloc is defined in header <cstdlib> since C++17.
1
void* aligned_alloc(std::size_t alignment, std::size_t size);
- Allocate
sizebytes of uninitialized storage whose alignment is specified byalignment(implicitly creating objects in the destination area). - The
sizeparameter must be an integral multiple ofalignment.
Parameters
| Parameter | Description |
|---|---|
alignment | Specifies the alignment. Must be a valid alignment supported by the implementation. |
size | Number of bytes to allocate. An integral multiple of alignment. |
Return Value
On success, returns the pointer to the beginning of newly allocated memory. To avoid a memory leak, the returned pointer must be deallocated with std::free or std::realloc.
On failure, returns a null pointer.
Notes
Size requirement — If
sizeis not an integral multiple ofalignment, the function returnsnullptr(DR460).Alignment restriction — The
alignmentmust be supported by the implementation.
Many POSIX implementations require it to be a power of two and a multiple ofsizeof(void*)(same asposix_memalign).
Fundamental alignments are always supported: ifalignmentis a power of two and not greater thanalignof(std::max_align_t),aligned_allocmay simply callstd::malloc.Windows — MSVC’s runtime library does not support
std::aligned_alloc. Use_aligned_malloc/_aligned_freeinstead.Object creation —
aligned_alloconly allocates raw memory. For class/array types, you must explicitly construct objects (e.g., placementnew).
Example
Click Run ▶