title: Compiler (G++) seems to allocate more memory for instances of classes than it needs
body: <p>I am learning about how compilers represent C++ programs in assembly. I have a question about something that the compiler does that I can't make sense of. Here is some C++ code:</p>
  
  <pre><code>class Class1 {
  public:
    int i;
    char ch;
  };
  
  int main() {
    Class1 cls;
  }
  </code></pre>
  
  <p>Compiling with "g++ -S " outputs this (I've stripped out everything but the function definition):</p>
  
  <pre><code>main:
      push    ebp
      mov     ebp, esp
      sub     esp, 16
      mov     eax, 0
      leave
      ret
  </code></pre>
  
  <p>I don't understand the line <code>sub esp, 16</code>. Why would it allocate 16 bytes for an instance of this class that only requires 8 when you take into account <a href="http://en.wikipedia.org/wiki/Data_structure_alignment" rel="nofollow" title="Wikipedia on data structure alignment">data structure alignment and padding</a>? </p>
  
  <p>It should be </p>
  
  <pre><code>[int i - 4 bytes][char ch - 1 byte][padding - 3 bytes]
  </code></pre>
  
  <p>should it not?</p>
  
  <p>When I compiled the code with the class definition also including a double, i.e.</p>
  
  <pre><code>class Class1 {
  public:
    int i;
    char ch;
    double dub;
  }; 
  </code></pre>
  
  <p>it still allocated 16 bytes, which made sense in that case.</p>
  
  <p>So why does the compiler allocate 16 bytes when it only needs 8?</p>