I was going through the concept of structure member alignment and structure padding concept when I found that the size of this struct
...
struct nod
The padding and alignment of members of a struct
are completely at the discretion of the compiler, except that there cannot be any padding before the first member. With that said, compilers normally choose padding to serve alignment purposes, so that, in particular,
structs
, if the members of the first array element are aligned optimally then so will be the members of all the others.Subject to those and similar requirements, compilers typically choose the least amount of padding necessary (ideally no padding at all). If different member types have different alignment requirements, then the above considerations require struct
representations to be padded to a multiple of the size of the member with the most stringent alignment requirement. They may also require padding between members, depending on the types of the members and their order.
Described wonderfully here.
Suppose you have this structure:
struct {
char a[3];
short int b;
long int c;
char d[3];
};
Now, you might think that it ought to be possible to pack this structure into memory like this:
+-------+-------+-------+-------+
| a | b |
+-------+-------+-------+-------+
| b | c |
+-------+-------+-------+-------+
| c | d |
+-------+-------+-------+-------+
But it's much, much easier on the processor if the compiler arranges it like this:
+-------+-------+-------+
| a |
+-------+-------+-------+
| b |
+-------+-------+-------+-------+
| c |
+-------+-------+-------+-------+
| d |
+-------+-------+-------+
In the ''packed'' version, notice how it's at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it's hard for the processor, too. Therefore, most compilers will ''pad'' the structure (as if with extra, invisible fields) like this:
+-------+-------+-------+-------+
| a | pad1 |
+-------+-------+-------+-------+
| b | pad2 |
+-------+-------+-------+-------+
| c |
+-------+-------+-------+-------+
| d | pad3 |
+-------+-------+-------+-------+
This post explained how padding is done, not why it is done. Please refer haccks' answer for why it is done.
Remember theses two rules for padding:
Member a
in second structure is not followed by any member or member with larger alignment and it is also the largest alignment member which means--No Padding.
Read this answer for more detailed explanation.