3.1 Storage Order and Alignment

Every data type has alignment requirements mandated by the processor architecture. A processor will be able to efficiently process data if the processing word size matches processor's data bus size. For example, on a 32-bit machine, the processing word size is 4 bytes. Figure 3.1 illustrates how a correctly aligned integer value is stored in memory. The 4 bytes of the aligned integer A are stored as A0, A1, A2, and A3 in memory. As this integer is stored with correct alignment, the processor can fetch the complete word in a single 32-bit bus cycle.

Figure 3.1 Correctly Aligned Integer Values in Memory

The diagram illustrates how two correctly aligned integers A and B, written as [A0] [A1] [A2] [A3] and [B0] [B1] [B2] [B3] in memory where each integer has 4 bytes, can each be accessed in a single fetch operation.

If the same processor now attempts to access an integer variable X at an unaligned address, it cannot perform the read in a single bus cycle. Figure 3.2 illustrates an incorrectly aligned integer value stored in memory.

Figure 3.2 Incorrectly Aligned Integer Value in Memory

The diagram illustrates an integer X, composed of bytes X0, X1, X2, and X3 in memory but incorrectly offset so that its bytes are spread across two addresses as [?] [X0] [X1] [X2] and [X3] [?] [?] [?], where [?] are arbitrary data bytes that are not associated with X. This integer would require two fetch operations; one for bytes X0, X1, and X2 and one for X3.

The processor has to issue two fetch instructions to read the complete misaligned integer and so takes twice as long as for an aligned integer. In short, the addresses of memory chunks should be in multiples of their sizes. If an address satisfies this requirement, it is said to be properly aligned. The consequences of accessing data via an unaligned address can range from slower execution to program termination.