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);
  • Allocate size bytes of uninitialized storage whose alignment is specified by alignment (implicitly creating objects in the destination area).
  • The size parameter must be an integral multiple of alignment.

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

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 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 creationaligned_alloc only allocates raw memory. For class/array types, you must explicitly construct objects (e.g., placement new).

Example

Click Run ▶

References

  1. C++ documentation
This post is licensed under CC BY 4.0 by the author.