liveBook · Manning

Alignment

As explained in Modern C, Third Edition

Alignment is the implementation-defined requirement that an object or structure member begin at an address suitable for its type.

Alignment describes the byte positions at which an object of a type can start. Objects of many noncharacter types cannot start at an arbitrary byte; they typically require an address suitable for their type. section 12.7

Structure members may need to start at particular positions, such as word boundaries. The compiler can insert byte padding between members to achieve this; there is no padding at the beginning of a structure. section 6.3.4

A pointer cast does not make an address suitably aligned for the target type. Converting a pointer to a differently typed pointer when it is not properly aligned is invalid; misaligned access can also cause a bus error on some systems. section 12.7 section 15.1.2

 int main(void) {
   enable_alignment_check();
   /* An overlay of complex values and bytes. */
   union {
     cdbl val[2];
     unsigned char buf[sizeof(cdbl[2])];
   } toocomplex = {
     .val = { 0.5 + 0.5*I, 0.75 + 0.75*I, },
   };
   printf("size/alignment: %zu/%zu\n",
          sizeof(cdbl), alignof(cdbl));
   /* Run over all offsets, and crash on misalignment. */
   for (size_t offset = sizeof(cdbl); offset; offset /=2) {
     printf("offset\t%zu:\t", offset);
     fflush(stdout);
     cdbl* bp = (cdbl*)(&toocomplex.buf[offset]); // align!
     printf("%g\t+%gI\t", creal(*bp), cimag(*bp));
     fflush(stdout);
     *bp *= *bp;
     printf("%g\t+%gI", creal(*bp), cimag(*bp));
     fputc('\n', stdout);
   }
 }

This program overlays complex values with bytes, then casts pointers at progressively smaller offsets to demonstrate the consequences of misalignment. section 12.7

C's alignof and alignas notation appears in declarations that inspect a type's alignment or request alignment for an object. section 12.7

How Modern C, Third Edition covers it

How deep it goes
Defines type alignment and demonstrates misaligned access with byte-offset pointer casts and a bus-error example.
Examples
Uses padded structure members and a byte-buffer overlay of complex values tested at progressively smaller offsets.
What it assumes
Assumes familiarity with C types, pointers, structures, and object representations.
What you can do after
Diagnose misaligned pointer conversions by examining byte offsets and their effects on typed access.
How it connects
Connects alignment to structure padding, object representation, and pointer conversions.

Also explained in

Compare how 2 books explain alignment →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.