开发者

Why doesn't size of struct is equals to sum of sizes of its individual member types? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Why isn’t sizeof for a struct equal to the sum of sizeof of each member?

I guess similar (duplicate) questions must have been asked on SO before. But I'm unable to find them. Basically I don't know what to search for. So asking it here.

Why doesn't size of struct is equals to sum of sizes of its individual member types? I'm using visual C++ compiler.

For example, assuming 32-bit machine. {=> sizeof(int) == 4; sizeof(char) == 1; sizeof(short) == 2; }

  struct {
      int k;
      char c;
  } s;

The size expected is 4+1 = 5; but sizeof(s) gives 8. Here char is occupying 4 bytes instead of 1. I don't know the exact reason for this but my guess is compiler is doing so for efficiency purposes.

struct{
 long long k;
 int i;
} s;

expected size is 4+4 = 8 (on 32 bit machine) and 8+4=12 (on 64 bit mach开发者_如何转开发ine). But strangely sizeof(s) give 16. Here both int & long long are occupying 8 bytes each.

  1. What is this thing called?
  2. What exactly is going on?
  3. Why is compiler doing this?
  4. Is there a way to tell compiler to stop doing this?


It is because the compiler uses padding to bring each element into word alignment that is specific to the architecture for which you are compiling.

It can be for one of several reasons but usually:

  1. Because some CPU's simply cannot read a long or long long multi-byte value when it isn't on an address multiple of its own size.

  2. Because CPU's that can read off-aligned data may do it much slower than aligned.

You can often force it off with a compiler-specific directive or pragma.

When you do this, the compiler will generate relatively inefficient code to access the off-aligned data using multiple read/write operations.


This is called padding; which involves adding some more bytes in order to align the structure on addresses that are divisible by some special number, usually 2, 4, or 8. A compiler can even place padding between members to align the fields themselves on those boundaries.

This is a performance optimization: access to aligned memory addresses is faster, and some architectures don't even support accessing unaligned addresses.

For VC++, you can use the pack pragma to control padding between fields. However, note that different compilers have different ways of handling this, so if, for example, you also want to support GCC, you'll have to use a different declaration for that.


The compiler can insert padding between members or at the end of the struct. Padding between members is typically done to keep the members aligned to maximize access speed. Padding at the end is done for roughly the same reason, in case you decide to create an array of the structs.

To prevent it from happening, you use something like #pragma pack(1).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜