tags:

views:

33

answers:

2

In code like the following, we typically have an implicit pad of 2 bytes at the end of the structure:

struct foo {
  int32_t x ;
  int16_t y ;
// <<< 2 bytes for total sizeof(foo) == 8
} ;

I was asked today what an aggregate initializer does with the extra two bytes:

foo o = { 0, 0 } ;

ie: is this going to be equivalent to

foo o ;
memset( &o, 0, sizeof(foo) ) ;

I had no clue, so I recommended not to depend on that (aggregate initialers are troublesome anyways so that's good general advise IMO).

Does anybody know if the C language spec says anything about what an aggregate initialization does with implicit padding when the platform ABI requires such padding for the specific structure in question?

A: 

I'm reasonably certain there's no requirement about initialization of padding. Just for example, it would be entirely legal for an implementation to add padding to every struct, and have it store a tag telling what type of structure it is to support run-time type checking. In such a case, most structs would contain padding that was always non-zero.

Jerry Coffin
+2  A: 

Quoting from the C99 standard, "Representation of types", 6.2.6:

When a value is stored in an object of structure or union type, including in a member object, the bytes of the object representation that correspond to any padding bytes take unspecified values.

In short, it is not specified by the language; it's up to the C compiler/interface implementor.

Michael Foukarakis