1
votes

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.

1
The compiler is free to insert arbitrary padding between a and b. However, in practice, it's unlikely to do so here. - Oliver Charlesworth
@OliCharlesworth Do you mean that it is unlikely for the compiler to do so, or the developer? Didn't understand the last part of your comment :) - user3407764
@user3407764: As Oli didn't mention the developer, I'm gonna go with the compiler. I believe the point was that, while the spec says a compiler MAY insert padding, few would bother to in this circumstance. - Scott Hunter
If the default structure member alignment is, say 8 bytes, then fields with size that is not a multiple of 8 will be padded with extra bytes until their size is a multiple of 8. If the last field is one byte, then 7 more will be added to the size of the struct to make it match the 8-byte multiple. - DNT
@ScottHunter He might not have mentioned a developer, but I felt like the last line implied it somehow. - user3407764

1 Answers

1
votes

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.