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.)

3
  • 4
    8-byte packing/alignment possibly? Commented Nov 13, 2013 at 13:18
  • could you please speify compiler setting for alignment Commented Nov 13, 2013 at 13:18
  • I don't think it's 8-byte alignment, since the size of a struct that contains exactly 3 ints is 12. Commented Nov 13, 2013 at 13:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

yay, thanks! Now I'm curious: why is this happening?
@urinieto as far as I know this is always about memory alignment and the data structure padding section is more relevant.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.