I know this is done by the compiler, but I would like to understand what the compiler would do for me. For example:
struct MixedData
{
short z;
char x;
char y;
};
int main(void)
{
printf("%d\n", sizeof(struct MixedData));
return 0;
}
The size of the structure would be: 4 Why did it give that result? and what would be its possible memory addresses? I also have another doubt, when I have an array of structures, is it always necessary to do some padding? And I'm also confused with the terms "alignment" and "padding". What I understand is that "alignment" refers to the way each member is located in memory and the padding is the bytes necessary to calculate the memory address of the member that follows an X member. I don't know if I'm right or not. I was also seeing that the compiler needs to align the structure to be more efficient for the CPU, but what if it doesn't align it properly? Could someone explain to me an example demonstrating its inefficiency?
You have a data type short (2 bytes) and 2 char (2 * 1 byte), this adds up to 4 bytes.
Assuming a 64-bit system
Suppose the following structure:
In a 32-bit system, it would remain in memory:
Now, if the structure is declared as follows:
In a 32-bit system, it would remain in memory:
Here is an article in English that explains in more detail and step by step with examples this topic of alignment and padding ( Alignment and padding ).
On the other hand, the " packing " option is provided by some compilers to force padding not to be used . The problem with this option is that the code generated to access non-aligned addresses may not be optimal and contain bugs. In addition, compatibility is lost since some architectures do not support this functionality.
I hope I was able to shed some light on the subject.