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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With