[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);
- It reserves a block of
sizebytes whose start address is a multiple ofalignment. The bytes are not initialized. sizehas to be an integral multiple ofalignment(for example,aligned_alloc(64, 256)is fine,aligned_alloc(64, 100)is not).- Typical use: buffers that must start on a cache-line (64 B) or SIMD-register boundary, or DMA buffers that a device expects at a page boundary.
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
If the allocation works, you get a pointer to the first byte of the block. The block belongs to the same allocator as malloc, so release it with std::free (or resize it with std::realloc); never with delete. Forgetting this leaks memory.
If the allocation fails, the return value is a null pointer, so check it before use.
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
The program below prints each address modulo 1024. The malloc result usually leaves a non-zero remainder, while the aligned_alloc(1024, 1024) result always prints 0. The example is adapted from the cppreference example for std::aligned_alloc.
Click Run ▶