Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of struct is more than expected [duplicate]

Tags:

c++

memory

struct

I already read this question: struct padding in c++ and this one Why isn't sizeof for a struct equal to the sum of sizeof of each member?

and I know this isn't standardized but still I believe it's a legit question.

Why is the size of this struct 16 on a x64 system?

struct foo { char* b; char a;};

The effective size would be 8 + 1 = 9, but I know there's padding involved. Anyway I thought a would only be padded to reach the size of an int, i.e. with other 3 bytes giving a total of 12 bytes.

Is there any reason why the specific compiler (gcc) thought it should have 16 bytes as a size?

Wild guess: is it possible that the biggest type (e.g. double or in this case x64 pointer) will dictate the padding to use?

like image 258
Dean Avatar asked Oct 20 '25 13:10

Dean


1 Answers

Likely the compiler is aligning the struct on an 8-byte word boundary to improve access speed. A struct size of 9 is probably going to slow down the CPU quite a bit with unaligned accesses (plus the stack pointer should never be on an odd address). A size of 12 (3 padding bytes), would work, but some operations, like the FPU operations, prefer an alignment of 8 or 16 bytes.

like image 106
owacoder Avatar answered Oct 22 '25 05:10

owacoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!