Recently I was learning about the topic of memory alignment and related issues and it led me to a following program:
#include <cstdio>
#include <cstdint>
struct XX
{
uint8_t a;
uint32_t b;
uint16_t d;
uint64_t c;
};
int main()
{
printf("\n\ntype size: %zu\n", sizeof(XX));
XX one;
XX two;
XX three;
printf("addresses of one-three:\n\t%p\n\t%p\n\t%p\n", reinterpret_cast<void *>(&one), reinterpret_cast<void *>(&two), reinterpret_cast<void *>(&three));
printf("\ndifference of addresses between one and two: %lu\n", reinterpret_cast<unsigned long>(&one) - reinterpret_cast<unsigned long>(&two));
printf("difference of addresses between two and three: %lu\n", reinterpret_cast<unsigned long>(&two) - reinterpret_cast<unsigned long>(&three));
printf("alignment of type alone: %zu\n", alignof(XX));
XX arr[2];
printf("\ndifference of addresses in array: %lu\n", reinterpret_cast<unsigned long>(&arr[1]) - reinterpret_cast<unsigned long>(&arr[0]));
printf("alignment of array type: %zu\n", alignof(XX[]));
}
I compiled this with GCC 8.1.0 as:
g++ -std=c++17 -O0 main.cpp
The ouput says that:
- alignment is 8-byte,
- size is 24 bytes,
- XX instances differ by 24 bytes inside the array (contiguous memory - no surprise), but by 32 bytes as free-standing variables.
Why are there excessive 8 bytes between the free-standing variables?