+ 3
[Solved] Someone please explain the output of this C code
I was trying to see how memory in structure is allocated in contagious manner so I wrote this small program. https://code.sololearn.com/cYdEJECvwA95/?ref=app Here in `Name1` I'm allocating 29 bytes but the output is showing 32 bytes? But when I'm allocating 20 bytes for `Name2` it outputs the expected 20 bytes. Can someone please explain why I'm getting 32 bytes in the first case instead of 29?
2 Respostas
+ 3
All structures in C have a specific 'alignment', and to uphold that alignment, the compiler inserts 'padding' in between the members of a structure. See
https://en.m.wikipedia.org/wiki/Data_structure_alignment
In the Test struct, the compiler introduces a padding of 3 bytes, so that the next float member can be placed on a 4 byte boundary (32 % 4 = 0), which is why the difference between `salary` and `name1` members is 32 bytes. Here is an example from the same Wikipedia page linked abovd
https://en.m.wikipedia.org/wiki/Data_structure_alignment#Typical_alignment_of_C_structs_on_x86
+ 4
I was unaware of this "alignment" and "padding" concepts.
Thanks for the references and answering XXX 🙏🙏
[Edit]
After studying a bit I found that..
The padding is added to avoid the wastage of CPU cycles. But it wastes memory instead.
So if we don't want to waste any memory but are ready to waste CPU cycles we need to use #pragma pack(1), it makes 1 word = 1 byte. So memory allocated for "Name" will be 29 bytes.
https://code.sololearn.com/cSTpa1QYDL1D/?ref=app