I roughly know about Alignment and have read cppreference's Objects and alignment and Wikipedia's Data structure alignment . However I still have some doubts. I'm mainly interested in C++, but the question applies to C too as it uses mostly the same rules for alignment.
I know that padding is added to increase the efficiency of data access, because on some architectures accessing a value at an address multiple of its size is faster/better (alignment).
- Is that the only reason why padding is used?
If so, consider the following structures:
struct A {
int i;
char c;
};
struct B {
struct A a;
char d;
};
On my architecture (x86_64), the compiler places 3 bytes of padding at the end of A
so that sizeof(A)==8
and sizeof(A[2])==16
, and other 3 bytes of padding at the end of B
, so that sizeof(B)==12
.
I understand that aligning A
to 8 bytes makes storing it in an array more efficient. But it doesn't seem to be useful at all, when A
is placed inside B
.
If everything so far is correct, then I'm wondering:
- Why padding is placed at the end of types, instead of limiting it to between elements of aggregated types (e.g. struct or array) and never at the end?
An example of what I mean: wouldn't it be better if the compiler decided that sizeof(A)==5
, sizeof(B)==6
, sizeof(A[2])==13
(3 bytes of padding between the elements, but not at the end)?