Why is my union's size bigger than I expected?

前端 未结 5 1685
滥情空心
滥情空心 2021-01-18 06:13

When I print the size of a union like this:

union u {
  char c[5];
  int i;
} un;

using this:

int _tmain(int argc, _TCHAR*          


        
相关标签:
5条回答
  • 2021-01-18 06:35

    Thanks for your suggestions. I tried this with a lots of examples and looks that union size is equivalent to (size of max element)+ padding(depending upon the size of highest datatype used).

    0 讨论(0)
  • 2021-01-18 06:45

    The alignment of your union must be the largest alignment of any of its members. This is 4. Therefore, the size of the union must be aligned to that size. It could have been 5 (as c is the largest member of the union), but because the alignment of the union as a whole is 4, the size of the union is padded to 8.

    Note that this is just for VC++. The standard does not specifically require it. Though it does allow implementations to pad types as needed, which VC++ does. GCC could do something different, and there could be compile-time switches you could employ to change this behavior.

    0 讨论(0)
  • 2021-01-18 06:51

    enter image description hereCompiler adds few bytes for alignment

    0 讨论(0)
  • 2021-01-18 06:53

    The sizeof operator produces the size of a variable or type, including any padding necessary to separate elements in an array of that type such that everything is still correctly aligned. Since your union has an int member, it needs to be 4-byte aligned, so its "natural" size gets rounded upwards to the next multiple of 4 bytes.


    The ffffff98 is because you're compiling with signed char. Using %x with an argument that is not unsigned int causes undefined behaviour; what you're seeing is sometimes called sign-extension. The result of your aliasing is 0x98 reinterpreted as char, which is -104. This retains its value on being promoted to int (this is called the default argument promotions), and the int -104 when aliased as unsigned int becomes 0xffffff98.

    0 讨论(0)
  • 2021-01-18 06:53

    The compiler can add padding wherever it wants to structs, unions, and classes to speed memory accesses. You are seeing the effect of that. For Visual C++, the padding is usually a multiple of the size of the largest member type. In this instance, the largest member is an int, therefore it pads the union with 3 unused bytes to make the total size 8.

    0 讨论(0)
提交回复
热议问题