In C++, what does `struct alignas(32) Block` guarantee, and why could `new Block` return a misaligned pointer before C++17?
answer
- alignof and sizeof both become 32
- only strengthens, never weakens
- beyond the default new alignment
- operator new with std::align_val_t
basics
~20 salignas(32) makes alignof(Block) 32 and rounds sizeof up to a multiple of 32, so stack and static objects land on 32-byte boundaries. Before C++17, new ignored such extended alignment; since C++17 it calls operator new(std::size_t, std::align_val_t).
solid answer
~40 sAn `alignas` specifier requests a stricter alignment: `struct alignas(32) Block { float lanes[8]; };` has `alignof(Block) == 32` and `sizeof(Block)` a multiple of 32, and the compiler aligns automatic and static objects accordingly. It can only strengthen: asking for less than the natural alignment is ill-formed, and Clang reports `requested alignment is less than minimum alignment`. An alignment above `alignof(std::max_align_t)` is **extended**, and support for it is implementation-defined. Heap allocation is the trap: before C++17, `new Block` called `operator new(std::size_t)`, which only guarantees a fundamental alignment, so the C++14 build on Apple clang 21 returned addresses 16 bytes off a 32-byte boundary. C++17 (P0035R4) added `operator new(std::size_t, std::align_val_t)`, chosen automatically for types aligned beyond `__STDCPP_DEFAULT_NEW_ALIGNMENT__` (16 on that platform), and `std::allocator` uses it too, so `std::vector<Block>` is aligned.
code
cpp · 15 lines#include <cstdint>
#include <cstdio>
#include <memory>
#include <vector>
struct alignas(32) Block { // e.g. for 256-bit SIMD loads
float lanes[8];
};
int main() {
std::printf("sizeof %zu alignof %zu\n", sizeof(Block), alignof(Block));
auto p = std::make_unique<Block>(); // C++17: operator new(std::size_t, std::align_val_t)
std::vector<Block> v(3);
std::printf("heap %% 32 = %zu, vector %% 32 = %zu\n",
reinterpret_cast<std::uintptr_t>(p.get()) % 32,
reinterpret_cast<std::uintptr_t>(v.data()) % 32);
}go deeper
Know that alignas asks for a stricter alignment and that alignof reports it.
Explain that alignas also rounds sizeof, cannot weaken alignment, and that extended alignments are implementation-defined.
Diagnose misaligned heap objects in pre-C++17 code or custom allocators, and know the align_val_t overloads, the default new alignment and aligned_alloc.
Decide which types justify over-alignment, given its memory cost and the allocator support every library in the build must provide.
## What alignas does The **alignment-specifier** `alignas(N)` or `alignas(T)` raises the alignment requirement of a variable, a data member or a class. For `struct alignas(32) Block { float lanes[8]; };`: - `alignof(Block)` is 32, although its member only needs 4. - `sizeof(Block)` is rounded up to a multiple of 32, so array elements stay aligned; here the data is exactly 32 bytes. - Every `Block` the compiler places itself, as a local, a global or a member of another struct, sits on a 32-byte boundary, and an enclosing struct inherits at least that alignment. Typical reasons are SIMD loads that require or prefer aligned addresses, hardware DMA buffers and lock-free structures that pack flags into low pointer bits. ## The rules on alignas itself 1. The value must be a power of two that the implementation supports in that context; an unsupported extended alignment makes the program ill-formed. 2. If a declaration carries several specifiers, the strictest one wins. 3. The combined request may **not** be weaker than the natural alignment. `struct alignas(2) Narrow { int x; };` is ill-formed, and Clang says `requested alignment is less than minimum alignment of 4 for type 'Narrow'`. Lowering alignment needs a compiler extension such as packing. 4. If one declaration of a class or variable has an alignment-specifier, its definition must have the same one. ## Fundamental, extended and new-extended alignment The draft distinguishes three ranges: | Term | Meaning | Value on Apple clang 21, arm64 | |---|---|---| | fundamental alignment | at most `alignof(std::max_align_t)`, supported everywhere | up to 8 | | extended alignment | greater than `alignof(std::max_align_t)`; support is implementation-defined | above 8 | | new-extended alignment | greater than `__STDCPP_DEFAULT_NEW_ALIGNMENT__` | above 16 | On x86-64 Linux, `alignof(std::max_align_t)` is typically 16; the numbers are the ABI's, so query them rather than memorize them. ## The heap allocation trap A `new`-expression gets memory from an allocation function. Up to C++14 the only one was `operator new(std::size_t)`, which returns storage suitably aligned for any object with a **fundamental** alignment and knows nothing about the type. A `Block` that needs 32 therefore received whatever the allocator happened to return. The code example shows it: built with `-std=c++14`, both `std::make_unique<Block>()` and `std::vector<Block>` returned addresses with remainder 16 modulo 32. Using such an object is undefined behaviour, and an aligned SIMD load from it can fault. C++17 adopted **P0035R4**, "Dynamic memory allocation for over-aligned data": - New overloads `operator new(std::size_t, std::align_val_t)` and the matching `operator delete` forms take the alignment as an argument. - A `new`-expression for a type whose alignment exceeds `__STDCPP_DEFAULT_NEW_ALIGNMENT__` calls the aligned overload automatically. - `std::allocator<T>::allocate` must return storage for an array of `T`, and libc++ obtains it through the aligned `operator new` when the alignment exceeds the default (its `__is_overaligned_for_new` check), so containers of over-aligned types are aligned. The same program built with `-std=c++17` printed remainder 0 for both. GCC documents this as `-faligned-new`, "enabled by default for `-std=c++17`", and a `-Waligned-new` warning, enabled by `-Wall`, for a `new` of an over-aligned type that uses an allocation function without an alignment parameter, for example a class-specific `operator new`. ## Pitfalls that remain - **Custom allocators and class-specific `operator new`** written before C++17 ignore the alignment unless updated to take `std::align_val_t`. - **`std::malloc` and C APIs** know nothing about `alignas`; use `std::aligned_alloc` (C++17), check the C library's rules on the size argument, and free it with `std::free`. - **Placement into a byte buffer** needs the buffer declared `alignas(Block)`, as in `alignas(Block) std::byte storage[sizeof(Block)];`. - **Passing by value** to functions is fine; the compiler aligns the parameter's storage. ## Over-alignment has a cost Raising alignment is not free. Every `Block` now takes a multiple of 32 bytes, every struct that contains one inherits the 32-byte alignment and may gain padding, and stack frames that hold one must be realigned. Use `alignas` where a measured requirement exists, such as an aligned SIMD load or a hardware constraint, and assert it with `static_assert(alignof(Block) == 32);` so the requirement is visible in code review. ## The point to make `alignas` is a request the compiler honours for objects it places itself; the heap honours it only through the C++17 aligned allocation functions. A strong answer gives both facts, the default new alignment threshold, and the C++14 symptom.
- How do you allocate over-aligned raw memory without a new-expression?Call `::operator new(size, std::align_val_t{32})` and release it with `::operator delete(p, std::align_val_t{32})`, or use `std::aligned_alloc(32, size)` from C++17, freed with `std::free`. Mixing the families, such as freeing aligned `operator new` memory with `std::free`, is undefined behaviour.
- Does alignas on a member change the enclosing struct?Yes. A member declared `alignas(32) float lanes[8];` makes the enclosing struct's alignment at least 32, inserts padding before that member as needed, and rounds the struct's `sizeof` up to a multiple of 32. The over-alignment propagates to every type that contains it, including heap allocation of the outer type.
- alignas can reduce a type's alignment to pack it tighter.
- new has always returned memory aligned for any type, whatever its alignas.
- std::vector of an over-aligned type is misaligned even in C++17.
- alignas changes only alignof, never sizeof.
- std::malloc respects the alignas of the type the memory is later used for.
Assumes C++17 or later for aligned operator new (P0035R4); C++14 builds call operator new(std::size_t) and may return under-aligned storage for over-aligned types.