1

I am getting 56 bytes for the following. Can anyone explain how is that?

#include <stdio.h>

typedef struct how_many_bytes {
    long s[4];
    char c, e;
    int i[2];
    char *d;    
} How_Many_Bytes;

int main(){    
    printf("%lu ", sizeof(How_Many_Bytes));
}

Shouldn't it be (4*8) + 1 + 1 + 2(for padding) + 4 + 4 + 8 = 52 bytes

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
ivesingh
  • 31
  • 1
  • 2
  • 3

2 Answers2

3

Because it's a 64-bit machine, so the padding is 6 instead of 2 in your calculation.

Also, you should use %zu to print size_t.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • So upto char e the size is 34 bytes and then when it gets to int you are saying it will be 6 padding which will start from 40 and then 48 after 2 ints? If it was 32-bit machine would the ints start from 36? – ivesingh Oct 09 '13 at 03:08
  • @user2844889 Exactly. – Yu Hao Oct 09 '13 at 03:09
  • The 4-byte `int`s do not need to be padded out to an 8-byte boundary; 2 bytes here is correct. The extra 4 bytes of padding are before the 8-byte pointer object. – caf Oct 09 '13 at 03:44
0

Your analysis is correct, except that there is an additional 4 bytes padding before the char *d member. This is so that the d member is aligned on an 8-byte boundary.

The pahole output for this structure on x86-64 is:

struct how_many_bytes {
        long int                   s[4];                 /*     0    32 */
        char                       c;                    /*    32     1 */
        char                       e;                    /*    33     1 */

        /* XXX 2 bytes hole, try to pack */

        int                        i[2];                 /*    36     8 */

        /* XXX 4 bytes hole, try to pack */

        char *                     d;                    /*    48     8 */

        /* size: 56, cachelines: 1 */
        /* sum members: 50, holes: 2, sum holes: 6 */
        /* last cacheline: 56 bytes */
};      /* definitions: 1 */

No matter how you rearrange the members of this structure, you won't be able to do better than 6 bytes in total of padding. The sum of the sizes of the members is 50 bytes, and the maximum alignment of the structure members is 8, so even if you arrange the members in the optimal order there will be 6 bytes of padding at the end of the structure to round its size up to the next biggest multiple of 8.

caf
  • 233,326
  • 40
  • 323
  • 462