title: Does C initialize structure padding to zero?
body: <p>If a C compiler pads a structure in order to align the fields to their native alignment, and that structure is then initialized, is the padding initialized to zero?</p>
  
  <p>For example the following structure:</p>
  
  <pre><code>typedef struct foo_t_ {
      int  a;
      char b;
      int  c;
      char d;
  } foo_t;
  </code></pre>
  
  <p>On many systems this (poorly designed) structure would have a <code>sizeof(foo_t)</code> of 16, with a total of 6 bytes of padding, 3 bytes after each of the chars.</p>
  
  <p>If we initialize the structure like:</p>
  
  <pre><code>foo_t foo = { .a = 1, .b = '2' };
  </code></pre>
  
  <p>then the fields <code>foo.a</code> will be set to 1 and <code>foo.b</code> will be set to the character '2'. The unspecified fields (`foo.c' and 'foo.d') will automatically be set to 0. The question is, what happens to the 6 bytes of padding? Will that also automatically be set to 0? or is it undefined behavior?</p>
  
  <p>The use case is that I will be calculating hashes of data structures:</p>
  
  <pre><code>foo_t foo = { .a = 1, .b = '2' };
  foo_t bar = { .a = 1, .b = '2' };
  uint32_t hash_foo = calc_hash(&amp;foo, sizeof(foo));
  uint32_t hash_bar = calc_hash(&amp;bar, sizeof(bar));
  </code></pre>
  
  <p>and I want to be sure that <code>hash_foo</code> and <code>hash_bar</code> are the same. I could guarantee this by first using <code>memset()</code> to clear the structures, then initializing them, but it seems cleaner to use C initialization instead.</p>
  
  <p>In practice, GCC on my system does clear the padding as well, but I don't know if that is guaranteed.</p>