5

I realized there's a memory overhead in my structs when they contain a pointer. Here you have an example:

typedef struct {
    int num1;
    int num2;
} myStruct1;

typedef struct {
    int *p;
    int num2;
} myStruct2;

int main()
{
    printf("Sizes: int: %lu, int*: %lu, myStruct1: %lu, myStruct2: %lu\n", sizeof(int), 
        sizeof(int*), sizeof(myStruct1), sizeof(myStruct2));
    return 0;
}

This prints the following in my 64-bit machine:

Sizes: int: 4, int*: 8, myStruct1: 8, myStruct2: 16

Everything makes sense to me except the size of myStruct2, which I thought it would only be 12 instead of 16 (sizeof(int*) + sizeof(int) = 12).

Could anyone explain me why this is happening? Thank you!

(I'm pretty sure this must have been asked somewhere else, but I couldn't find it.)

Oriol Nieto
  • 5,409
  • 6
  • 32
  • 38

1 Answers1

7

That is padding the standard says there may be unnammed padding within a struct or at the end but not at the beginning. The draft C99 standard section 6.7.2.1 Structure and union specifiers paragraph 13 says:

[...]There may be unnamed padding within a structure object, but not at its beginning.

and paragraph 15 says:

There may be unnamed padding at the end of a structure or union.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • yay, thanks! Now I'm curious: why is this happening? – Oriol Nieto Nov 13 '13 at 13:23
  • 1
    @urinieto as far as I know this is always about [memory alignment](http://en.wikipedia.org/wiki/Data_structure_alignment) and the [data structure padding section](http://en.wikipedia.org/wiki/Data_structure_alignment#Data_structure_padding) is more relevant. – Shafik Yaghmour Nov 13 '13 at 13:25