3

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?

Community
  • 1
  • 1
Dean
  • 6,610
  • 6
  • 40
  • 90

2 Answers2

11

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.

owacoder
  • 4,815
  • 20
  • 47
1

It is because of memory alignment. By default memory is not aligned on one bye order and this happens. Memory is allocated on 4-byte chunks on 32bit systems.

You can change this behavior by setting __attribute__((packed, aligned(x))) when you define your structure. By this memory is allocated on x-byte chunks.

AKJ88
  • 713
  • 2
  • 10
  • 20
  • Question: is it allocated in 8-byte chunks on x64 systems? – Dean Oct 06 '15 at 15:24
  • Dynamically-allocated memory has alignment suitable for any type, which in practice means the most restrictive type. Pointers should be 8-byte aligned on x86_64, so dynamically-allocated memory should be at least 8-byte aligned. – Useless Oct 06 '15 at 15:28
  • As far as I know memory alignment is also 4bytes for x86_64, but for stack boundary and as Useless has mentioned for pointers its 8bytes. – AKJ88 Oct 06 '15 at 15:40