Site Tools


c-memory-alignment

C memory alignment

C memory alignment refers to the byte offset where data types must start. Structs have padding to align fields, and _Alignof queries alignment requirements. Proper alignment improves performance (cache lines, SIMD) and is required by hardware.

Use alignment awareness to understand struct layout, optimize for cache, and meet hardware requirements.

Example

// compile: gcc -std=c11 -o alignment alignment.c
// run: ./alignment
// description: struct padding and alignment
 
#include <stdio.h>
#include <stdalign.h>
 
struct Packed {
    char a;
    int b;
    char c;
};
 
struct Optimized {
    int b;
    char a;
    char c;
};
 
int main() {
    printf("Packed layout:\n");
    printf("  size: %zu\n", sizeof(struct Packed));
    printf("  alignof: %zu\n", alignof(struct Packed));
    printf("  a offset: %zu\n", offsetof(struct Packed, a));
    printf("  b offset: %zu\n", offsetof(struct Packed, b));
    printf("  c offset: %zu\n", offsetof(struct Packed, c));
 
    printf("Optimized layout:\n");
    printf("  size: %zu\n", sizeof(struct Optimized));
    printf("  alignof: %zu\n", alignof(struct Optimized));
 
    return 0;
}

Common patterns

Alignment requirements:

  • Char: 1 byte
  • Short: 2 bytes
  • Int: 4 bytes
  • Long: 8 bytes (on 64-bit)
  • Struct: alignment of largest member

Padding:

  • Compiler inserts padding between members for alignment
  • Wasted space but improves performance
  • Reorder fields to minimize padding

Cache efficiency:

  • Keep related data together
  • Minimize struct size with smart ordering
  • False sharing: unrelated data on same cache line

Hardware alignment:

  • SIMD operations require specific alignment
  • Atomic operations may require alignment
  • Hardware may fault on misaligned access

_Alignof and alignas:

  • _Alignof(type): required alignment
  • _Alignas(type): enforce alignment
  • C11 feature, not in C99
c-memory-alignment.md · Last modified: by 127.0.0.1