Alignment of Objects in C Programming

0
In C programming, the alignment of objects is a critical concept that impacts how objects are allocated in memory. This article will delve into the details of object alignment in C.

Complete Object Types and Alignment

Complete object types have alignment requirements that place restrictions on the addresses at which objects of that type may be allocated. An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated. An object type imposes an alignment requirement on every object of that type. Stricter alignment can be requested using the `_Alignas` keyword.

Fundamental Alignment

A fundamental alignment is a valid alignment less than or equal to `_Alignof (max_align_t)`. Fundamental alignments shall be supported by the implementation for objects of all storage durations. The alignment requirements of the following types shall be fundamental alignments:
  • All atomic, qualified or unqualified basic types
  • All atomic, qualified or unqualified enumerated types
  • All atomic, qualified or unqualified pointer types
  • All array types whose element type has a fundamental alignment requirement
  • All types specified in clause 7 as complete object types
  • All structure or union types all of whose elements have types with fundamental alignment requirements and none of whose elements have an alignment specifier specifying an alignment that is not a fundamental alignment

Extended Alignment

An extended alignment is represented by an alignment greater than `_Alignof (max_align_t)`. It is implementation-defined whether any extended alignments are supported and the storage durations for which they are supported. A type having an extended alignment requirement is an over-aligned type.

Representation of Alignments

Alignments are represented as values of the type `size_t`. Valid alignments include only fundamental alignments, plus an additional implementation-defined set of values, which may be empty. Every valid alignment value shall be a nonnegative integral power of two.

Order of Alignments

Alignments have an order from weaker to stronger or stricter alignments. Stricter alignments have larger alignment values. An address that satisfies an alignment requirement also satisfies any weaker valid alignment requirement.

Querying Alignment Requirement

The alignment requirement of a complete type can be queried using an `_Alignof` expression. The types `char`, `signed char`, and `unsigned char` shall have the weakest alignment requirement.

Comparing Alignments

Comparing alignments is meaningful and provides the obvious results:
  • Two alignments are equal when their numeric values are equal.
  • Two alignments are different when their numeric values are not equal.
  • When an alignment is larger than another it represents a stricter alignment.
Tags

Post a Comment

0Comments
Post a Comment (0)