Memory Alignment And Padding
Here is a small struct,
#include <stdint.h>
struct S {
uint8_t c1;
int16_t s;
int32_t i;
uint8_t c2;
};
The fields add up to 8 bytes. A uint8_t is 1, an int16_t is 2, an int32_t is 4, and another uint8_t is 1. But on a typical platform, sizeof(struct S) is 12. The compiler added 4 bytes that you did not write. That gap is padding.
This article explains alignment and padding covering what alignment means, why the CPU wants it, where padding comes from and how to reduce it. The examples are in C, but the ideas apply to any language that compiles to native code.
Alignment
Memory is addressed 1 byte at a time, but the CPU does not read it 1 byte at a time. It reads in chunks. A chunk size is called a word, and it depends on the architecture. Common sizes are 4 bytes and 8 bytes.
An address is n-byte aligned when it is a multiple of n, where n is a power of 2. Every address is 1-byte aligned, since every number is a multiple of one. A 4-byte aligned address is divisible by 4. An 8-byte aligned address is divisible by 8.
A value is aligned when its address is a multiple of its size. A 4-byte int32_t is aligned when it sits at an address divisible by 4. An 8-byte double is aligned when it sits at an address divisible by 8. This is called natural alignment.
#include <stdalign.h>
/* query the alignment the compiler actually uses for a type */
_Static_assert(alignof(int32_t) == 4, "expected 4");
_Static_assert(alignof(double) == 8, "expected 8");
_Alignof (C11) returns a type's alignment as a size_t constant expression. Before C11 there was no portable way to ask the compiler what alignment it chose for a type.
Alignment matters because when a value sits at an aligned address, it fits inside a single word, and one read is enough. When it does not, the value may span 2 words. The CPU then has to read both words and combine the pieces. That extra work costs cycles.
A 4-byte value that starts at offset 3 spans 2 4-byte words.
0 1 2 3 | 4 5 6 7
word 0 [ ][ ][ ][x]
word 1 [x][x][x][ ]
value bytes 3 4 5 6
On some architectures, unaligned access is not just slow. On older ARM processors, it is not allowed at all and triggers a fault. On x86, the hardware handles it, but with a penalty. On AArch64, unaligned access to normal memory often works, but access to device memory, which is uncached, requires alignment. Cache lines are usually 64 bytes, and a value that crosses a cache line boundary touches 2 lines, which costs more to fetch.
The hardware knows nothing about structs. It only knows about addresses and transfer sizes. Everything else is convention.
Note: Alignment is an ABI property, not a language rule, the ABI being the set of layout rules the compiler and linker follow for a given platform. On common platforms a built-in type's alignment equals its size, but that can differ elsewhere: a
longis 8 bytes on 64-bit Linux and macOS, 4 bytes on 32-bit systems, and still 4 bytes on 64-bit Windows, with the alignment following the size. So sizeof and offsetof results depend on the target and the compiler flags; do not hardcode offsets measured on one platform or share struct definitions across differently built compilation units.
Padding
A struct is a sequence of fields laid out in the order you declare them. Each field must start at an aligned address. When the current offset does not satisfy the next field's alignment, the compiler inserts unnamed bytes between them. This is internal padding.
There is also tail padding. After the last field, the compiler may add bytes so that the total size of the struct is a multiple of the struct's own alignment. The struct's alignment is the largest alignment among its fields. Tail padding exists so that every element of an array of structs is aligned. Element n is at base plus n times sizeof, and that address must be aligned.
Here is the same example.
struct S {
uint8_t c1;
int16_t s;
int32_t i;
uint8_t c2;
};
The fields add up to 8 bytes, but the struct is 12 bytes on a typical platform. The layout looks like this.
offset 0 1 2 3 4 5 6 7 8 9 10 11
+--+--+--+--+--+--+--+--+--+--+--+--+
|c1|p1| s | i |c2|p2|p2|p2|
+--+--+--+--+--+--+--+--+--+--+--+--+
c1 takes 1 byte at offset 0. Then 1 padding byte aligns s to offset 2. s takes 2 bytes. i takes 4 bytes starting at offset 4. c2 takes 1 byte at offset 8. Then 3 padding bytes round the total size up to 12, which is a multiple of 4, since int32_t has alignment 4 and that is the struct's alignment.
The padding bytes are unused. They exist only to push later fields to aligned addresses.
Ordering Members
Padding depends on declaration order. If you group fields by alignment, you can reduce or remove it. Reordering the same fields gives a different result.
struct S {
uint8_t c1;
uint8_t c2;
int16_t s;
int32_t i;
};
This version is 8 bytes with no padding. c1 and c2 share the first 2 bytes. s is aligned at offset 2. i is aligned at offset 4. The total is already a multiple of 4.
A simple rule is to declare fields from largest alignment to smallest. C keeps fields in declaration order and never reorders them; the padding between them is decided by the ABI, not chosen ad hoc by the compiler. Not every language is this predictable; keep that in mind.
Unions and Alignment
A union stores one value at a time in shared storage. All members start at offset 0.
union U {
int32_t i;
float f;
};
A union's alignment is the largest alignment among its members. Its size is the largest member size, rounded up to that alignment. There is no padding between members, since they overlap, but tail padding still applies so that an array of unions stays aligned.
Packing
Packing tells the compiler to remove padding, usually by setting alignment to 1 byte. C has no standard way to spell this, so every compiler has its own syntax. GCC and Clang accept __attribute__((packed)); MSVC uses #pragma pack(1).
/* GCC, Clang */
struct __attribute__((packed)) Packed {
uint8_t c1;
int64_t l;
uint8_t c2;
};
/* MSVC */
#pragma pack(push, 1)
struct Packed {
uint8_t c1;
int64_t l;
uint8_t c2;
};
#pragma pack(pop)
On a 64-bit platform, this struct is 10 bytes. The unpacked version is 24 bytes. Every access to l is now unaligned. On x86 the hardware handles it, though the penalty is small on modern CPUs. On some architectures it can fault. Packing is useful for matching a fixed external layout, such as a hardware register map, or for saving memory in a large array. It is not a good default. Measure before adopting it.
Packed structs have one downside of their own. Taking the address of a packed member, such as &p.l, produces an int64_t * that points to an unaligned object. Dereferencing that pointer is undefined behavior, even on x86 where the hardware would have handled the access fine. Copy the value through memcpy if you need to pass it around by address.
Packing only removes padding. It does not change byte order or value representation.
C does have a standard way to do the opposite, raise alignment above the natural requirement. _Alignas(N) (C11, also spelled alignas via <stdalign.h>) forces a type or field to N-byte alignment. _Alignof(T) queries the alignment the compiler chose for a type. _Alignof(T) is an integer constant expression, so it works in _Static_assert.
Arrays
Tail padding is what makes arrays work. If a struct has alignment 8 but size 9, then the 2nd element of an array would start at offset 9, which is not 8-byte aligned. The compiler prevents this by making the size a multiple of the alignment.
This means a struct can be larger than the sum of its fields even with no internal padding, purely because of tail padding. sizeof is a layout result, not a sum.
Takeaways
- Alignment is a property of addresses. A value is aligned when its address is a multiple of its size.
- The CPU reads memory in words. Aligned data fits in one word. Unaligned data may need more.
- The compiler inserts padding to keep each field aligned, and tail padding to keep arrays aligned.
- Field order affects struct size. Ordering from largest to smallest alignment usually minimizes padding.
- Packing removes padding but can slow down or break access. Use it for a specific reason, and measure.
_Alignas/_Alignof(C11) let you raise or query alignment portably, unlike packed or#pragma packwhich are compiler-specific.- Allocation alignment is a separate concern from struct layout.
mallocalready returns memory aligned for any fundamental type; stricter needs requirealigned_alloc(C11) or a platform equivalent.
References
- Eric S. Raymond, The Lost Art of C Structure Packing, http://www.catb.org/esr/structure-packing/
- Wikipedia, Data structure alignment, https://en.wikipedia.org/wiki/Data_structure_alignment
- GCC, Common Type Attributes (packed), https://gcc.gnu.org/onlinedocs/gcc/Common-Type-Attributes.html
- cppreference,
_Alignas/_Alignof, https://en.cppreference.com/c/language/_Alignas