title: Local Variables Alignment in C code
body: <p>I'm trying to understand how packing of a struct variable affects the way local variables on the stack are assigned address.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  struct s
  {
      short s1;
      short s2;
      short s3;
  };
  
  int main()
  {
      struct s myStruct1;
      struct s myStruct2;
  
      myStruct1.s1 = 1;
      myStruct1.s2 = 2;
      myStruct1.s3 = 3;
  
      myStruct2.s1 = 4;
      myStruct2.s2 = 5;
      myStruct2.s3 = 6;
  
      int i = 0xFF;
  
      printf("Size of struct s: %d", sizeof(myStruct1));
      return 0;
  }
  </code></pre>
  
  <p>In my program above, I have 2 struct variables and 1 integer. The GCC compiler has decided to assign addresses like this: </p>
  
  <pre><code>&amp;i          0x00007FFFFFFFDF0C
  &amp;myStruct1  0x00007FFFFFFFDF10
  &amp;myStruct2  0x00007FFFFFFFDF20
  </code></pre>
  
  <p>There is no padding within the struct - the size of the struct is 6 bytes.</p>
  
  <p>Question is why is myStruct2 on a 2-byte boundary when it could have been placed on the next 6 bytes after myStruct1?</p>