Home > Enterprise >  Can C add padding between struct members, even if they are ordered in decreasing alignment?
Can C add padding between struct members, even if they are ordered in decreasing alignment?

Time:12-15

struct Foo {
    int a;
    char b;
}

Will it be guaranteed in this case that b will have an offset of sizeof(int) in the struct? Will it be guaranteed that members will be packed together as long as all alignment requirements are being met, no padding required (Not taking into account the padding at the end to align the structures size to the largest member)?

I am asking this because I would like to know if simply fwrite()ing a struct to a save file can cause problems if the layout of a struct is not consistent across platforms, because then each save file would be specific to the platform on which it was created.

CodePudding user response:

There are no guarantees. If a compiler wishes to insert unnecessary padding between structure members, it can do so. (For example, it might have determined that a particular member could be handled much more efficiently were it eight-byte aligned, even though it doesn't require alignment at all.)

Portable code intended for interoperability should not fwrite structs. Aside from the potential of differences in padding, not all platforms use the same endianness, nor the same floating point representation (if that's relevant).

CodePudding user response:

Strictly speaking, the C standard makes no guarantees regarding padding inside of a struct, other than no padding at the beginning.

That being said, most implementations you're likely to come across tend to perform padding in a consistent manner (see The Lost Art of Structure Packing). In your particular example however there's a potential for inconsistency as an int is not necessarily the same size on all platforms.

If you used fixed width types such as int32_t and int8_t instead of int and char then you're probably OK. Adding a static_assert for the size of the struct can help enforce this.

You do however need to worry about endianness, converting each field to a known byte order before saving and back to the host byte order after reading back.

  • Related