Is a struct with a single char array member guaranteed to have a predictable size?

Viewed 131

Consider the following struct:

struct alignas(8) Foo {
    char data[8];
};

Is it guaranteed by the Standard that sizeof(Foo) == 8?

From a layman's point of view, it should be true, because 8 chars don't need any padding to have an alignment of 8. And it seems to be true in practice on GCC, Clang, and MSVC (live demo).

However, padding and alignment is a tricky business, and I couldn't find any information that strictly forbids implementations from adding extraneous padding - i.e. sizeof(Foo) == 16 might be possible too?

I've found the following so far:

  • sizeof(char[8]) == 8 is guaranteed (see here), thus sizeof(Foo) >= 8)
  • Foo does not have leading padding, since it is a standard layout type (see here)
  • At least one more knowledgeable person - the author of std::bit_cast - apparently believes there is no padding - see this article

(Interestingly, if this fact is untrue, it would seem to imply that structs can have arbitrarily large size, which is a bit strange.)

1 Answers

Implementations are free to add as much padding as they want. The size of a type is constrained to at minimum the size of its contents, but that's all the standard requires.

I can't really point to something that isn't there, so I can't link to the part of the standard that doesn't impose a limitation.

Broadly speaking, implementations won't do weird things to the sizes of types. And ABI requirements can limit implementations. But as far as the standard itself is concerned, there is no such requirement.

Related