Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Firstly, while the specifics of padding are left up to the compiler, the OS also imposes some rules as to alignment requirements. This answer assumes that you are using gcc, though the OS may vary</p> <p>To determine the space occupied by a given struct and its elements, you can follow these rules:</p> <p>First, assume that the struct always starts at an address that is properly aligned for <em>all</em> data types.</p> <p>Then for every entry in the struct:</p> <ul> <li>The minimum space needed is the raw size of the element given by <code>sizeof(element)</code>.</li> <li>The alignment requirement of the element is the alignment requirement of the element's base type. Notably, this means that the alignment requirement for a <code>char[20]</code> array is the same as the requirement for a plain <code>char</code>.</li> </ul> <p>Finally, the alignment requirement of the struct as a whole is the maximum of the alignment requirements of each of its elements.</p> <p>gcc will insert padding after a given element to ensure that the next one (or the struct if we are talking about the last element) is correctly aligned. It will <em>never</em> rearrange the order of the elements in the struct, even if that will save memory.</p> <p>Now the alignment requirements themselves are also a bit odd.</p> <ul> <li>32-bit Linux requires that 2-byte data types have 2-byte alignment (their addresses must be even). All larger data types must have 4-byte alignment (addresses ending in <code>0x0</code>, <code>0x4</code>, <code>0x8</code> or <code>0xC</code>). Note that this applies to types larger than 4 bytes as well (such as <code>double</code> and <code>long double</code>).</li> <li>32-bit Windows is more strict in that if a type is K bytes in size, it must be K byte aligned. This means that a <code>double</code> can only placed at an address ending in <code>0x0</code> or <code>0x8</code>. The only exception to this is the <code>long double</code> which is still 4-byte aligned even though it is actually 12-bytes long.</li> <li>For both Linux and Windows, on 64-bit machines, a K byte type must be K byte aligned. Again, the <code>long double</code> is an exception and must be 16-byte aligned.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload