Padding bytes are added between data members of a structure or class when they are needed to either fulfil the alignment requirements of any of those data members, or (more generally) to optimize access speed to those members.
Now, although the alignment requirements for types such as int
are not specified by the C++ Standard, and can vary (or not vary) between 32-bit and 64-bit builds for the same underlying chip (such as the Intel x86-64 systems), the alignment requirement for the char
type (and also signed char
and unsigned char
) is specified by the Standard! From cppreference:
The weakest alignment (the smallest alignment requirement) is the
alignment of char
, signed char
, and unsigned char
, which equals 1; the
largest fundamental alignment of any type is implementation-defined
and equal to the alignment of std::max_align_t
(since C++11).
So, as the alignment requirement for the b
member is 1, no padding is required between a
and b
. In your case, the alignment requirement for int
is 4 bytes, so two padding bytes must be added before the c
member. Thus, 2 × sizeof(char)
(= 2) + 2 padding bytes + 2 × sizeof(int)
(=8) gives a total size of 12 bytes.