Definition
Alignment is a restriction on the addresses at which a value may start in memory. An address is aligned to bytes when it is a multiple of ; the alignment requirement is always a power of two, such as 1, 2, 4 or 8. In C the compiler fixes an alignment requirement for every object type; a 4-byte integer commonly needs 4. Some instructions add requirements of their own. Size says how many bytes a value occupies; alignment says at which addresses it may begin.
The idea
A receiver stores a 5-byte packet at address 1000. Byte 0 is a message type, and bytes 1 to 4 hold a 32-bit count. All five bytes are present, yet the count starts at address 1001, which is not a multiple of 4. A program that reads the count as an ordinary 4-byte integer asks the processor for a 4-byte load from address 1001. Depending on the processor, that load works, works more slowly, or stops the program with a fault. In C the program is already wrong before the load runs.
Memory hardware moves data in fixed-width units. A processor with a 32-bit data path reads addresses 1000 to 1003 in one transfer, because they form one aligned word. A 4-byte value at 1001 occupies addresses 1001 to 1004 and straddles two words, so the hardware needs two transfers and must join the pieces, or it refuses. An aligned 4-byte value likewise never straddles a cache line, the block that a cache stores as a unit, or a page of virtual memory, because those blocks begin at multiples of their own power-of-two sizes. Aligned accesses up to the word size are therefore simpler and faster, and on many processors they happen as one indivisible step.
How it works
A program meets alignment requirements in three steps:
The compiler fixes each type’s requirement. Types are commonly aligned to their own size: a 2-byte
uint16_tto 2, a 4-byteuint32_tto 4. The 1-byte character typeschar,signed charandunsigned charhave alignment 1, so any address suits them. In C11, the 2011 edition of the C standard, the operator_Alignofgives a type’s requirement, and_Alignasasks for a stricter one.The compiler places objects accordingly. Every variable starts at an aligned address. Inside a structure the compiler inserts unused bytes before a member that would otherwise be misaligned (struct padding §4.27). Memory from
mallocis aligned for every ordinary type.Converted pointers carry the risk. Converting a pointer from one type to another, for example a byte pointer into a received packet to a
uint32_tpointer, keeps the address. Nothing moves the bytes to an aligned position.
Processors react to a misaligned access in different ways:
Arm Cortex-M0 and Cortex-M0+ processors (architecture Armv6-M) fault on every misaligned access, with a HardFault, the exception that Cortex-M processors raise for errors that have no more specific handler.
Cortex-M3, Cortex-M4 §6.3 and Cortex-M7 processors (Armv7-M) accept misaligned single 2-byte and 4-byte loads and stores, at some extra cost. They raise a UsageFault, the exception for misused instructions, for instructions that move several words at once, such as
LDRD(load two registers) andLDM(load multiple registers) and the matching stores, and for the exclusive accesses used to build atomic operations §9.8.x86 processors accept most misaligned loads and stores, but some vector instructions demand 16-byte alignment and fault without it.
Device registers reached through memory-mapped I/O §4.35 (input and output through ordinary memory addresses) usually must be accessed at their natural alignment and width.
C adds a rule of its own. Section 6.3.2.3 of C11 makes converting a pointer to a different object pointer type undefined behavior §4.12, behavior on which the standard places no requirement, if the result is not correctly aligned for the new type. The conversion is already the error, before any access. Compilers rely on the rule: since every uint32_t pointer may be assumed to hold a multiple of 4, a compiler may merge two neighboring 4-byte loads into one LDRD, which faults on a Cortex-M4 at a misaligned address although that processor accepts each 4-byte load alone.
Two portable methods read a value that may be misaligned. The first reads the bytes one at a time and combines them with shifts; a 1-byte read is never misaligned. The second copies the bytes with memcpy, the library function that copies a given number of bytes, into a local uint32_t variable that the compiler has aligned. For a small constant length, compilers turn the copy into one load where the processor accepts misaligned loads and into byte loads where it does not, so it costs nothing extra.
Worked example
A packet of 5 bytes, 01 00 00 01 02 in hexadecimal, arrives at address 0x20000100. Byte 0 is message type 1, and bytes 1 to 4 are a count in big-endian §4.21 order, most significant byte first, so the count starts at 0x20000101.
Alignment check. For , the remainder of an address divided by 4 is held in its lowest 2 bits. 0x20000100 ends in the hexadecimal digit 0, binary 0000, so its remainder is 0 and it is 4-aligned. 0x20000101 ends in binary 0001, so its remainder is 1: in decimal it is . The count is misaligned. Reading its bytes one at a time avoids the problem and gives .
Copy, then convert. Copying bytes 1 to 4 into an aligned uint32_t variable on a little-endian host, which stores the least significant byte first, gives the variable the value 0x02010000, which is . Converting from big-endian to host order reverses the four bytes and gives 0x00000102, which is 258. The copy solved alignment and the conversion solved byte order; neither does the other’s job.
Why a structure cast reads the wrong bytes. A native C structure for this packet, a uint8_t type field followed by a uint32_t count, does not match the packet. The count needs an offset that is a multiple of 4, so the compiler puts it at offset 4, the smallest multiple of 4 that is at least 1, and leaves bytes 1 to 3 unused; the structure is bytes long. Laid over the 5-byte packet, it reads the count from packet bytes 4 to 7: one byte of the real count, 02, and 3 bytes that are not part of the packet.
Stated precisely
Let be an address and an alignment requirement, a power of two. The address is aligned for exactly when , where is the remainder of divided by . Because is a power of two, , where is bitwise AND. The smallest aligned address not below is , where is rounded up; in bitwise form it is , where inverts every bit. For and : , which rounds up to 251, and .
Section 6.2.8 of C11 states that every complete object type has an alignment requirement, an integer that the implementation (the compiler and library for one target) defines; that every valid alignment is a nonnegative integral power of two; and that char, signed char and unsigned char have the weakest alignment, 1. Section 6.3.2.3 adds that converting a pointer to a different object pointer type is undefined behavior if the result is not correctly aligned for the referenced type. A type’s size is always a multiple of its alignment, so when the first element of an array §14.5 is aligned, every element is.
Limits and common mistakes
Accepted by the processor is not correct C. A misaligned load that works on a Cortex-M4 or an x86 machine is still undefined behavior in C. The compiler may emit an instruction that faults, such as LDRD, and the same code faults on a Cortex-M0.
Misaligned is not indivisible. A misaligned value that straddles two words may be read or written in two parts, so another processor core, an interrupt handler §6.12 or a direct memory access §4.36 transfer can see half of an old value and half of a new one. A variable used in an atomic operation must be aligned.
A byte buffer has alignment 1. An array of uint8_t may start at any address. Declare it with _Alignas(4), or take it from malloc, when an aligned start matters; an alignment stricter than that of every ordinary type, such as 32 bytes for some vector data, needs aligned_alloc.
Aligned is not safe. Alignment says nothing about whether the bytes exist, whether the object still exists (object lifetime §4.1), whether C allows the access type (the strict aliasing rule §4.23), or which byte order the field uses (endianness).
Packed structures cost speed and portability. Common compilers offer a packed attribute for structures, which is not standard C. It removes the padding and makes the compiler generate safe code for each member access, but each such access may become several byte loads, and a member’s address passed on as an ordinary uint32_t pointer is misaligned again.
Tools find misaligned accesses. UndefinedBehaviorSanitizer §10.23, a run-time checker that the compiler inserts, reports them in a program built with -fsanitize=alignment.
Questions answered
Can a packed wire buffer be safely cast to a struct pointer?
No, not in portable C, and alignment is only the first of four reasons. A packed wire buffer is a sequence of bytes laid out by a protocol with no gaps between fields; casting it means converting its address to a pointer to a C structure and reading the fields through that pointer.
Alignment. A byte buffer has alignment 1, so its address need not be a multiple of the structure’s alignment, and a field can fall at an odd offset. Converting to a misaligned structure pointer is already undefined behavior, and the field reads may fault.
Layout. The compiler inserts unused bytes to align the structure’s members, so their offsets and the structure’s size can differ from the wire layout: a 1-byte type followed by a 4-byte count is 5 bytes on the wire but 8 bytes as a native structure, with the count at offset 4 instead of 1.
Byte order. The structure reads every integer in the host processor’s byte order, whatever order the protocol uses.
Type rules. When the buffer is declared as an array of bytes, reading it through a structure member of another type breaks C’s strict aliasing rule.
A compiler’s non-standard packed attribute removes the first two problems, for that compiler only. The portable method is to check that the buffer holds every byte the format requires, then decode each field from its byte offset with shifts, or copy it with memcpy into an aligned variable and convert its byte order.
Related entries: Strict aliasing and effective type (§4.23), Endianness (§4.21), Memory-mapped I/O (MMIO) (§4.35), Struct padding and packing (§4.27), Atomic operation (§9.8), UndefinedBehaviorSanitizer (§10.23). Further reading: [6, 26, 78].