Memory Alignment

1 / 5

Why Alignment?

  • CPU accesses aligned data faster
  • Misaligned may trap (SIGBUS)
  • SIMD requires 16/32/64-byte alignment
2 / 5

The Alignment Formula

aligned = (addr + alignment - 1) & ~(alignment - 1);

// Example: align 0x1004 to 16 bytes
// (0x1004 + 15) & ~15
// = 0x1013 & 0xFFF0
// = 0x1010
3 / 5

aligned_alloc Strategy

  1. Allocate extra: size + alignment + ptr_size
  2. Find aligned address in that space
  3. Store original pointer before it
  4. Return aligned address
4 / 5

Freeing

void aligned_free(void *ptr) {
    void *original = ((void**)ptr)[-1];
    free(original);
}
5 / 5
Use arrow keys or click edges to navigate. Press H to toggle help, F for fullscreen.