Alignment
Alignment is the address multiple an object must start on. An int typically wants a 4-byte address. A misaligned pointer is undefined behavior to dereference on some ABIs and merely slow on others.
Detailed Explanation
Every complete object type has an alignment, a power of two. _Alignof(T) (or alignof in C23) reports it. The compiler places objects so that address % _Alignof(T) == 0. malloc returns storage aligned for any standard type; C11 aligned_alloc and POSIX posix_memalign ask for a stricter alignment, which SIMD and DMA sometimes need.
A pointer cast does not change alignment. (int *)char_buf is defined as a pointer conversion and undefined as a dereference if char_buf is not 4-aligned. This is how packed protocol buffers bite people: you memcpy into an int, or you read bytes with shifts, or you use a compiler packed-struct extension and accept the cost.
Over-aligned types (_Alignas(16)) appear in the type. An automatic object with a large alignment may need extra stack padding. An array of over-aligned structs has a stride that is a multiple of that alignment.
_Alignas on a member raises that member's alignment and can raise the struct's. It does not remove the need for padding after a smaller member. offsetof tells you where the member actually sat.
Hardware varies. x86 allows many misaligned loads with a performance penalty. Some ARM settings fault. A portable program pretends they all fault. Sanitizers (-fsanitize=alignment) and UBSan will name the load.
Code Examples
#include <stdio.h>
#include <stdalign.h>
struct S {
char c;
int i;
};
int main(void)
{
printf("%zu %zu %zu\n",
alignof(char), alignof(int), alignof(struct S));
/* typical: 1 4 4 */
printf("%zu\n", offsetof(struct S, i));
/* typical: 4 — three bytes of padding after c */
return 0;
}#include <stdio.h>
#include <stdint.h>
#include <string.h>
int main(void)
{
unsigned char buf[8] = { 1, 0, 0, 0, 2, 0, 0, 0 };
int x;
memcpy(&x, buf, sizeof x); /* defined, even if buf is odd */
printf("%d\n", x); /* prints: 1 on little-endian */
return 0;
}Common Gotchas
`malloc` is aligned for standard types, not for 64-byte cache-line or AVX types
use `aligned_alloc` and check that the size is a multiple of the alignment (C11).
SIMD types often need 16- or 32-byte alignment
a stack `float v[4]` may not be enough without `_Alignas`.
Packed structs (`__attribute__((packed))`) are a compiler extension that create
Packed structs (`__attribute__((packed))`) are a compiler extension that create misaligned members on purpose