Memory alignment (source code)

= Memory alignment

<Memory alignment> restricts the <memory addresses> at which an object may begin. An alignment of $A$ <bytes> means that its starting byte address $a$ satisfies $a\bmod A=0$. For example, address $4096$ satisfies eight-byte <memory alignment>, whereas address $4100$ does not. Alignment is a constraint on location, rather than another name for an object's size.

In the <C programming language>, object types have alignment requirements; `_Alignof` queries a type's requirement and `_Alignas` can request a supported stronger requirement. The actual values depend on the implementation. The C11 draft distinguishes fundamental from implementation-supported extended alignments and requires valid alignment values to be powers of two.<C11 committee draft N1570>[section 6.2.8, paragraphs 1–6; sections 6.5.3.4 and 6.7.5]{ref}

An <application binary interface> makes such choices concrete. Under the ordinary AAPCS64 layout, a C structure containing a `char tag` followed by a `double value` has the character at offset $0$, seven unused padding <bytes>, and the double at offset $8$. Its total size is $16$ <bytes> and its alignment is $8$ <bytes>. The <application binary interface> aligns an aggregate as strictly as its most strictly aligned member and rounds the aggregate size up to a multiple of that alignment; this also keeps each element properly aligned in an array of these structures.<Procedure Call Standard for the Arm 64-bit Architecture by Arm>[sections 5.1, fundamental type sizes and alignments, and 5.10.1, aggregates]{ref}

This example is an explicit platform convention, rather than a universal promise that every C `double` needs eight-byte <memory alignment>. Likewise, a processor's ability to execute an unaligned load does not by itself relax the <C programming language>'s object-access requirements. Keeping the language rule, the <application binary interface> layout, and the machine instruction separate explains why a byte buffer cannot automatically be treated as a properly located object of any chosen type.