Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory overhead for structs with pointers in C [duplicate]

Tags:

c

pointers

memory

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

like image 385
Oriol Nieto Avatar asked Nov 13 '13 13:11

Oriol Nieto


1 Answers

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.

like image 113
Shafik Yaghmour Avatar answered Sep 23 '22 15:09

Shafik Yaghmour