Post

[C++] Memory: std::aligned_alloc

[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 size bytes whose start address is a multiple of alignment. The bytes are not initialized.
  • size has to be an integral multiple of alignment (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

ParameterDescription
alignmentSpecifies the alignment. Must be a valid alignment supported by the implementation.
sizeNumber 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 size is not an integral multiple of alignment, the function returns nullptr (DR460).

  • Alignment restriction — The alignment must be supported by the implementation.
    Many POSIX implementations require it to be a power of two and a multiple of sizeof(void*) (same as posix_memalign).
    Fundamental alignments are always supported: if alignment is a power of two and not greater than alignof(std::max_align_t), aligned_alloc may simply call std::malloc.

  • Windows — MSVC’s runtime library does not support std::aligned_alloc. Use _aligned_malloc / _aligned_free instead.

  • Object creation — aligned_alloc only allocates raw memory. For class/array types, you must explicitly construct objects (e.g., placement new).

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 ▶

References

  1. C++ documentation
  2. cppreference.com - std::aligned_alloc
This post is licensed under CC BY 4.0 by the author.