Alignment Pitfalls: Over-Alignment & Allocator Mismatches

Careless use of alignment can lead to pitfalls like over-aligning data, which wastes memory. More critically, if an `alignas` value represents an 'extended alignment' unsupported by the compiler, the program is ill-formed. Furthermore, standard allocators (like `malloc` or `new`) don't guarantee `alignas` compliance; specialized functions like `_aligned_malloc` or custom allocators are often needed to ensure aligned memory for dynamically allocated structures.

The top 3

  1. C++17's Fix: Over-Aligned Dynamic Allocations: Before C++17, `alignas` on dynamically allocated objects was often silently ignored by `operator new` for types requiring alignment greater than `std::max_align_t` (typically 8 or 16 bytes), creating a subtle bug where requested alignment was not guaranteed on the heap. C++17 introduced `operator new` overloads that accept `std::align_val_t`, ensuring `alignas` is respected for heap allocations.
  2. Misalignment's Hidden Costs: x86 vs. ARM Performance: While x86/x64 architectures often handle misaligned memory access by performing extra work (e.g., two cache line reads instead of one), leading to performance penalties, ARM and other architectures can outright crash with a bus error. This makes proper alignment a correctness requirement on some platforms, not just a performance optimization. Over-alignment can also lead to increased memory fragmentation and cache misses if not carefully managed.
  3. Allocator Pairing: The `aligned_alloc` vs. `malloc` Deallocation Trap: A critical pitfall arises from mismatched allocation and deallocation functions; for instance, C11's `aligned_alloc` requires `free()` for deallocation, while Microsoft Visual C++'s `_aligned_malloc` needs `_aligned_free()`. Using the wrong deallocation function for aligned memory can lead to undefined behavior, memory leaks, or crashes due to the allocator's internal bookkeeping mechanisms.

Sources

Open the full topic