Dynamic Memory Allocation for Over-Aligned Data

This lesson explains memory alignment in C++ 17 and how it fixes the holes in C++11/14 memory alignment.

We'll cover the following

Embedded environments, kernel, drivers, game development and other areas might require a non-default alignment for memory allocations. Complying those requirements might improve the performance or satisfy some hardware interface.

Memory Alignment

For example, to perform geometric data processing using SIMD[^simd] instructions, you might need 16-byte or 32-byte alignment for a structure that holds 3D coordinates:

[^simd]: Single Instruction, Multiple Data, for example, SSE2, AVX, see https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions

struct alignas(32) Vec3d { // alignas is available since C++11
    double x, y, z;
};
auto pVectors = new Vec3d[1000];

Vec3d holds double fields, and usually, its natural alignment should be 8 bytes. Now, with alignas keyword, we change this alignment to 32. This approach allows the compiler to fit the objects into SIMD registers like AVX (256-bit-wide registers).

Get hands-on with 1200+ tech skills courses.