I was exploring memory alignment and padding, and thought that I got the hang of it until I came across this:
struct Example {
int x1; // 4
char c; // 1 + 3 padding
int x2; // 4
};
static_assert(sizeof Example == 12, "Incorrect size"); // OK
struct Example2 {
long long x; // 8
Example y; // 12
// 4 bytes padding
};
static_assert(sizeof Example2 == 24, "Incorrect size"); // OK
struct Example3 {
unsigned char x[8]; // 8
unsigned char y[12]; // 12
// 4 bytes padding??
};
static_assert(sizeof Example3 == 24, "Incorrect size"); // ERROR
I am on a 64-bit system, using MSVC x64 compiler. Why does it always calculate memory alignments for structs with only array types as 1?
long long x;
requires the alignment 8, the compiler adds the 4 bytes padding to make elements in an array of Example2
properly aligned.
unsigned char x[8];
doesn't require any alignment, the elements in an array of Example3
do not need to be aligned, thus the compiler doesn't add padding bytes, but it can add them, it's implementation specific.