7

Consider this code:

// T is *any* type
struct str_T{
    T a, b;
};

I know that there's (almost always) padding between objects with different alignments because both members are of type T. But this time there's no different alignments. Can this assertion always pass?

static_assert(sizeof(str_T) == 2 * sizeof(T));
// i.e. padding-free
iBug
  • 35,554
  • 7
  • 89
  • 134
  • 1
    Related question : https://stackoverflow.com/questions/47324044/why-is-there-no-padding-in-the-structure-for-only-char-type-members – msc Nov 29 '17 at 05:31
  • Is it true that `_Alignof(str_T::a) == _Alignof(str_T::b)`? – iBug Nov 29 '17 at 06:07
  • Even if there is no padding between `struct` members, what about possible padding at the end of the `struct`? This would also be counted in the result of `sizeof`. – ad absurdum Nov 29 '17 at 06:07
  • 2
    @chux No, different struct types may certainly have different alignment requirements. Read your quote again: It's talking about *pointers* to structs, not the structs themselves. – Tom Karzes Nov 29 '17 at 06:35

2 Answers2

6

No, this is not guaranteed. Compiler can always decide to pad or to not pad extra bits between struct members. (Unless overridden)

Quoting from C11 draft, 6.7.2.1 Structure and union specifiers

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

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • So `T` may be `char` and `struct str_T` sized to 4 for some reason? – chux - Reinstate Monica Nov 29 '17 at 05:38
  • @chux Yes, this is a possibility. But being unspecified, I cannot quote an example of a compiler + flag requirement which can guarantee this behaviour. – Mohit Jain Nov 29 '17 at 05:41
  • So your conclusion is that it's not specified, but so far no implementation disobeys it? – iBug Nov 29 '17 at 08:49
  • @iBug Yes you are right. I am not aware of any implementation where the static assert would fail. But if it allowed to fail on conformant implementations. – Mohit Jain Nov 29 '17 at 13:37
1

No, There is no guaranteed that it's the same memory layout.

C11 6.7.2.1(p6):

a structure is a type consisting of a sequence of members, whose storage is allocated in an ordered sequence

The standard doesn't enforce any layouting rules.

msc
  • 33,420
  • 29
  • 119
  • 214