Reputation: 1432
According to Wikipedia, a structure containing a single byte and a four-byte integer, in this order, would require three additional bytes of padding because the four-byte integer has to be 4 bytes aligned.
A structure containing a four-byte integer and a single byte, in this order, would require no additional padding bytes because one byte will be 1-byte aligned?
The size of the first structure will be 8 but the size of the second structure will be 5?
What about another four-byte integer allocated in memory after the second structure above? Will it be allocated after a gap of 3 bytes so that it respect the 4 bytes alignment?
[update from comment:]
I forgot to mention my example is on a 32 bit system.
[UPDATE]
I just found out that pack instructions added at the beginning and end of a structure only apply to the members of the structure and does not propagate to other structures. This means if you have a structure of structures, you have to pack them individually, not just the parent structure.
Upvotes: 2
Views: 1466
Reputation: 154482
A missing consideration in data alignment and packing is that there are at least 2 aspects of data alignment.
Performance: Certain alignments of types, like a 4-byte int
often perform faster with an alignment on a matching (quad) address boundary. This is often a compiler default. Sometimes other lower performing alignments are possible. Compiler specific pack options may use this less optimal speed layout to achieve less padding.
Required: Certain alignments of types are required, like a 2-byte integer may cause a bus-fault on an odd address. Compiler specific pack options will not violate this. Packing may reduced padding, yet some padding may remain.
To answer OP's questions:
All are "maybe". It is compiler specific with consideration to its options and target hardware.
Upvotes: 0
Reputation: 36458
Upvotes: 4