Memory alignment is the placement of data in memory at addresses that are multiples of a certain number of bytes, corresponding to the architecture or data type. Proper alignment is critical for performance, correct hardware operation, and certain processor instructions.
Background.
In early computers, misalignment resulted in hardware failures (bus errors), and the computational power of processors was sensitive to unaligned data addresses. Even in modern architectures, proper alignment allows data access in a single cycle without penalty.
The Problem.
If a structure is placed without considering alignment, read/write operations may be slower or impossible (for example, crash on ARM or MIPS). Additionally, it disrupts interaction with low-level APIs, devices, or data serialization for network transmission.
The Solution.
In C++, to control alignment, the keyword alignas (C++11) and std::align can be used, as well as non-standard compiler attributes (__attribute__((aligned(N))) in GCC/Clang, __declspec(align(N)) in MSVC).
Example code:
struct alignas(16) MyStruct { int a; double b; char c; }; #include <iostream> #include <type_traits> int main() { std::cout << alignof(MyStruct) << std::endl; // 16 std::cout << sizeof(MyStruct) << std::endl; }
Key Features:
Does the order of struct member declarations affect the size and alignment of the structure?
Yes, the order of members directly determines the padding between them, which can add extra bytes to the size of the structure.
struct S1 { char a; int b; }; // usually sizeof==8 (on 4-byte alignment) struct S2 { int b; char a; }; // usually sizeof==8, but sometimes less padding
Can the size of the structure be reduced without disrupting alignment?
Yes, if larger members are grouped first and smaller ones later. Effectively align data considering their sizes:
struct S { double d; int i; char c; }; // better than disjointed
What happens if you work with unaligned addresses manually through pointers?
The C++ standard declares such behavior as undefined behavior, and some CPUs may raise SIGBUS or equivalent.
A programmer implemented a custom structure for SIMD processing without specifying alignment. As a result, the program crashes on some ARM devices while trying to operate on unaligned data.
Pros:
Cons:
In a project working with video data (SSE/AVX), alignas was used for buffer structures, allowing for efficient use of SIMD instructions at all times.
Pros:
Cons: