Size of Struct in C; GCC vs Actual Calculation
<p>According to <a href="http://www.c-faq.com/struct/align.html" rel="nofollow noreferrer">c_faq</a>,</p>
<pre><code>typedef struct  {
    char a[3];
    short int b;
    long int c;
    char d[3];
} T;
</code></pre>
<p><code>sizeof(T)</code> will return me 16 on a 32-bit gcc compiler. Because the alignment is 4, so to calculate, I should do this: <code>3+(1)+2+(2)+4+3+(1)</code>, where the brackets represent paddings. GCC concurs.</p>
<p>Based on that logic,  did some practices on my own with another question.</p>
<pre><code>typedef struct{
    char buf1[9];
    unsigned short s;
    double d;
    char buf2[3];
} S;
</code></pre>
<p><code>sizeof(S)</code> should return me 32 on a 32-bit gcc compiler. Because the alignment is 8, so to calculate, I should do this: <code>8+1+2+(5)+8+3+(5)</code>. However, gcc is telling me that <code>sizeof(S)</code> is 24.</p>
<p>I reckoned it's because of optimization, however, after messing with the <code>-O0</code> flag in gcc, <code>sizeof(S)</code> still results in 24.</p>
<p>I was using <code>gcc -m32 main.c</code> to compile.</p>
<p>What is going on here?</p>
<p>If I understood properly, the reason why my calculation and GCC's calculation do not match is because each compiler has their own way of handling struct data. Then what is a universal way of calculating the size of a struct? Or rather, what is the original way of calculating the size of a struct?</p>