Skip to content
BetterDL

Memory alignment

Also called: alignment, aligned word, word alignment, aligned access, unaligned access, aligned address

Placing each multi-byte word at an address that is a multiple of its size, so a 4-byte word starts at an address whose low two bits are 00.

In a byte-addressable memory, a 4-byte word could in principle start at any byte. It is aligned when it starts at a multiple of its size:

  • 2-byte words: even addresses (low bit 0)
  • 4-byte words: multiples of 4 (low two bits 00)
  • 8-byte words: multiples of 8 (low three bits 000)

Why bother? The memory hardware is built around whole words. An aligned word sits entirely inside one physical word and can be fetched in a single access. An unaligned word straddles two physical words: the hardware has to make two accesses and stitch the pieces together, or, on many processors, it simply refuses and raises an error.

Alignment also makes address arithmetic clean. For an aligned 4-byte word, the low two address bits are always 00, and the rest of the address is the word number.

Compilers lay out data aligned automatically, sometimes leaving unused padding bytes between fields to do it.

0
128
0
64
1
32
0
16
1
8
1
4
0
2
0
1

Worked example

Example

Which addresses are aligned?

Which of these byte addresses can start an aligned 32-bit word: 1A₁₆, 2C₁₆, 37₁₆, 40₁₆?

  1. 1.

    Check the low two bits (multiple of 4).

  2. 2.

    1A₁₆ = 0001 1010: ends 10. Not aligned.

  3. 3.

    2C₁₆ = 0010 1100: ends 00. Aligned (44 = 4 × 11).

  4. 4.

    37₁₆ = 0011 0111: ends 11. Not aligned.

  5. 5.

    40₁₆ = 0100 0000: ends 00. Aligned (64 = 4 × 16).

Common mistakes

  • Checking for even addresses only. A 4-byte word needs a multiple of 4, not just of 2.

  • Assuming unaligned accesses are free. They take two accesses, or fail outright on many processors.

Practice Memory alignment

Interactive questions with instant feedback and a worked solution for every wrong answer.

Learn it step by step

Memory alignment is taught in Memory and Basic CPU / Computer Architecture.