What are objects and alignment in C ?

Object

An object is a container where data is stored in the execution environment. C programs create, access, and destroy these objects. Objects contain values that can have specific types. Every object has the following characteristics:

  • Size
  • Type
  • Value
  • Lifetime - temporary or equal to storage duration
  • Storage duration
  • Alignment requirement - can be determined by _Alignof
  • Identifier (optional)

Objects Composition

Objects are made up of continuous byte (one or more) sequences, each having CHAR_BIT bits.

Object representation

The bytes can be copied into an object of type unsigned char[n] where n is the object’s size. Objects with the same object representation are said to be equal. However, the opposite is not true because every bit of the object does not necessarily participate in the object representation.

Trap Representation - when no value of object type is represented in the object representation. Padding bits and multiple representations of integer types are a few exceptions that allow trap representations.

Effective Type

Objects have an effective type that determines which lvalue accesses are valid, as shown below:

Figure 1: Effective Types of objects

Example

In the following example, S is an aggregate type with a member of the int type. In line 5, read from *x must take place after write through *y.

struct S { int a, b; };
void func(int *x, struct S *y, struct S s)
{
for (int i = 0; i < *x; i++) *y++ = s;
}

Alignment

Every object type has an alignment requirement. This is an integer value of type size_t. This represents the number of bytes present between successive addresses. Objects of this type can be allocated at these addresses. Alignment values are non-negative and have powers of two.

_ Alignof can find out the alignment requirement`.

Example

The following code demonstrates alignment. Objects of struct M can be allocated at any address as both its members can be allocated at any address. However, Objects of struct N can be allocated at 4-byte boundaries since N.i must be allocated at 4-byte boundaries. This is because an int's alignment requirement is usually 4:

#include <stdio.h>
#include <stdalign.h>
struct M { // size = 2, alignment = 2 (cumulative total)
char x; // size = 1, alignment = 1
char y; // size = 1, alignment = 1
};
struct N { // size = 8, alignment = 4
int i; // size = 4, alignment = 4
char c; // size = 1, alignment = 1
// three bytes padding
};
int main(void)
{
printf("sizeof(struct M) = %zu\n", sizeof(struct M));
printf("alignof(struct M) = %zu\n", alignof(struct M));
printf("sizeof(struct N) = %zu\n", sizeof(struct N));
printf("alignof(struct N) = %zu\n", alignof(struct N));
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved