Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it guaranteed that there's no padding between values of the same type?

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
like image 642
iBug Avatar asked Nov 29 '17 05:11

iBug


2 Answers

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

like image 199
Mohit Jain Avatar answered Sep 30 '22 11:09

Mohit Jain


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.

like image 27
msc Avatar answered Sep 30 '22 10:09

msc