Sitram
Sitram

Reputation: 1432

Data structure padding and memory allocation

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.

  1. 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?

  2. The size of the first structure will be 8 but the size of the second structure will be 5?

  3. 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

Answers (2)

chux
chux

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

Paul Roub
Paul Roub

Reputation: 36458

  1. Maybe, maybe not. You might be on an architecture that likes padding to 8-byte boundaries.
  2. Possibly. Never assume the same, predictable binary representation of a C structure across compilers. Or even across different options in the same compiler.
  3. Maybe. In the example architecture, probably. But the gap may in fact be larger if the compiler's libraries tend to allocate bigger chunks.

Upvotes: 4

Related Questions