I'm using the Code::Blocks IDE with the GNU GCC compiler.
struct test
{
char a;
char e;
char f;
char b;
char d;
};
sizeof(test)
returns 5
.
I read this answer: Why isn't sizeof for a struct equal to the sum of sizeof of each member?
How come there is no padding after the last char
, so that sizeof(test)
returns 6
or 8
? There are a ton more questions I could ask once I add short
and int
, etc. But I think this question is good for now. Would not padding make it easier for the processor to work with the struct?
padding makes things bigger. packing makes things smaller.
The answer to that lies in how a CPU accesses memory. Typically a CPU has alignment constraints, e.g. a CPU will access one word at a time, or a CPU will require data to be 16byte aligned, etc. So to make sure that data is aligned according to the constraints of the CPU, padding is required.
Structure Padding in C:The structure padding is automatically done by the compiler to make sure all its members are byte aligned. Here 'char' is only 1 byte but after 3 byte padding, the number starts at 4 byte boundary. For 'int' and 'double', it takes up 4 and 8 bytes respectively.
Padding increases the performance of the processor at the penalty of memory. In structure or union data members are aligned as per the size of the highest bytes member to prevent the penalty of performance.
The alignment of a char
is only 1, so there is no need for the struct to be padded out to meet a larger alignment requirement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With