Determining the alignment of C/C++ structures in relation to its members

There are two closely related concepts to here:

  1. The alignment required by the processor to access a particular object
  2. The alignment that the compiler actually uses to place objects in memory

To ensure alignment requirements for structure members, the alignment of a structure must be at least as strict as the alignment of its strictest member. I don’t think this is spelled out explicitly in the standard but it can be inferred from the the following facts (which are spelled out individually in the standard):

  • Structures are allowed to have padding between their members (and at the end)
  • Arrays are not allowed to have padding between their elements
  • You can create an array of any structure type

If the alignment of a structure was not at least as strict as each of its members you would not be able to create an array of structures since some structure members some elements would not be properly aligned.

Now the compiler must ensure a minimum alignment for the structure based on the alignment requirements of its members but it can also align objects in a stricter fashion than required, this is often done for performance reasons. For example, many modern processors will allow access to 32-bit integers in any alignment but accesses may be significantly slower if they are not aligned on a 4-byte boundary.

There is no portable way to determine the alignment enforced by the processor for any given type because this is not exposed by the language, although since the compiler obviously knows the alignment requirements of the target processor it could expose this information as an extension.

There is also no portable way (at least in C) to determine how a compiler will actually align an object although many compilers have options to provide some level of control over the alignment.

Leave a Comment