What happens to padding bytes during initialization
27 Aug 2020 - John Z. Li
Define a struct like below:
struct A{
char c;
int i;
};
The actual memory layout is like
struct A{
char c;
//char d[3] three invisible padding bytes
int i;
};
because of alignment and padding.
Question: what happens to those padding bytes during initialization according to the C++ standard?
- Case one
A a{}; //value initialization
Zero initialization actually is performed while doing value initialization, all bytes of he initialized object is set to zero, including padding bytes.
- Case two
A a2 {'\0', 0}; //aggregate initialization
While doing aggregate initialization with
braced-init-list
, and the number of elements in thebraced-init-list
is equal with the number of elements of the struct, the padding bytes are left untouchedx, that is, padding bytes might contain arbitrary value. - Case three
A a3{.c='\0'}; //aggregate initialization
This is also aggregate initialization. Since the number of initializer clauses is less than the number of members of the struct, remaining members of the struct, as well as all padding bytes, are zero initialized.
Note: In the C programming language, wording is different, but the same rule applies.