title: C++ struct memory overhead in clang?
body: <p>Is there a per-struct memory overhead in clang? Usually the size of a struct is just the total size of all of its members. But this doesn't seem to be the case in clang:</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  struct Obj {
      int x;
      int y;
  };
  
  int main() {
      int a = 42;
      int b = 43;
      Obj obj = {100, 101};
      int c = 44;
  
      cout &lt;&lt; *(&amp;a - 0) &lt;&lt; endl;  // 42
      cout &lt;&lt; *(&amp;a - 1) &lt;&lt; endl;  // 43
      cout &lt;&lt; *(&amp;a - 2) &lt;&lt; endl;  // On clang this prints garbage value instead of 101, how strange...
      cout &lt;&lt; *(&amp;a - 3) &lt;&lt; endl;  // 101
      cout &lt;&lt; *(&amp;a - 4) &lt;&lt; endl;  // 100
      cout &lt;&lt; *(&amp;a - 5) &lt;&lt; endl;  // 44
  
      return 0;
  }
  </code></pre>
  
  <p>I compiled with <code>clang++ program.cpp</code>, no optimization. Version:</p>
  
  <pre><code>Ubuntu clang version 3.4-1ubuntu3 (tags/RELEASE_34/final) (based on LLVM 3.4)
  Target: x86_64-pc-linux-gnu
  Thread model: posix
  </code></pre>
  
  <p>The memory location at <code>(&amp;a - 2)</code> doesn't seem to be used at all. I inserted the following code between the declaration of <code>int a</code> and <code>int b</code>:</p>
  
  <pre><code>*(&amp;a - 2) = -1234;
  </code></pre>
  
  <p>This will later print <code>-1234</code> instead of a garbage value on <code>*(&amp;a - 2)</code>, indicating that clang didn't write to this value after creating <code>Obj obj</code>, which makes me wonder why clang reserved it in the first place.</p>
  
  <p>On gcc this behaves differently. First, the stack appears to grow toward higher memory addresses on gcc on my machine. Also, gcc took it upon itself to place the variable <code>c</code> right after <code>b</code>, so the it looks like this:</p>
  
  <pre><code>cout &lt;&lt; *(&amp;a + 0) &lt;&lt; endl;  // 42
  cout &lt;&lt; *(&amp;a + 1) &lt;&lt; endl;  // 43
  cout &lt;&lt; *(&amp;a + 2) &lt;&lt; endl;  // 44 gcc moved c here even without optimization
  cout &lt;&lt; *(&amp;a + 3) &lt;&lt; endl;  // 100
  cout &lt;&lt; *(&amp;a + 4) &lt;&lt; endl;  // 101
  </code></pre>
  
  <p>Compiled with <code>g++ program.cpp</code>. Version:</p>
  
  <pre><code> g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
  </code></pre>
  
  <p>Same behavour when I ported the program to C. Everything is run on a 64-bit Linux Mint 17.1. Can someone explain whether there is a greater purpose to clang's waste of 4 bytes of memory?</p>