user3407764
user3407764

Reputation:

Structure padding and alignment of byte-sized fields?

If I have a structure such as the one below, on a 32-bit machine, will there be any padding within the structure? As I understand it, the structure will align everything to it's largest field, so what if the largest field is a byte (uint8)?

struct s {
    uint8_t a[32];
    uint8_t b[64];
};

Thanks.

Upvotes: 1

Views: 412

Answers (1)

this
this

Reputation: 5290

There may be padding between the members.

C standard 6.7.2.1(15): Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

(14) Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.

There is probably no padding between the members on a modern machine, but C doesn't guarantee it, so don't rely on it.

You can determine if there is padding using the ofsetoff() macro and then manage that with static assert.

Upvotes: 0

Related Questions