Home > Enterprise >  Weird allignment behaviour in C
Weird allignment behaviour in C

Time:03-26

#include <stdio.h>

int main(void)
{
  int a = 0x4565;
  long ch1;
  int ch2;

  printf("%p %p %p\n", &ch2, &ch1, &a);
  printf("%zu %zu %zu\n", sizeof(long), sizeof (int), _Alignof(a));

  return 0;
}

Output:

0x7fffebb487dc 0x7fffebb487e0 0x7fffebb487ec
8 4 4

If the alignment of int is 4 then why the space for the variable had not been allocated in 0x7fffebb487e8 ? Why compiler gives extra 4 byte space (padding) ?

This happens only if int is allocate after variable which is the size of 8 (like pointer, long, long long). If the preceding variable is type of int i.e. having size of and alignment of 4 the compiler gives no padding.

I am confused. Please help me. Thank you.

CodePudding user response:

Without optimization on, the compiler is assigning space naïvely and is working with the stack from high addresses to low, which is the direction the stack grows in.

Starting from an aligned address which ends in 0 (hex), it assign four bytes for a, putting it at an address that ends in C. Then, for the long ch1, it has to skip four bytes to get to the eight-byte-aligned address ending in 0. Finally, for ch2, it merely subtracts four bytes.

When you turn on optimization, a smarter algorithm will be used.

  • Related