Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

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

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* argv[])
{
    printf("size of union = %d ",sizeof(un));
    return 0;
}

I get an answer of 8 using Visual C++, but I expected 5. Why?

Well, for the same example, i did something like this:

int i1 = 0x98761234;
un.i = i1;
printf("
 un.c[0] = %x ",un.c[0]);
printf("
 un.c[1] = %x ",un.c[1]);
printf("
 un.c[2]= %x ",un.c[2]);
printf("
 un.c[3] = %x ",un.c[3]);
printf("
 un.c[4] = %x ",un.c[4]);
printf("size of union = %d ",sizeof(un));

i got results like

un.c[0] = 34;
un.c[1] = 12;
un.c[2] = 76;
un.c[3] = ffffff98;

why are there 6fs at un.c[3]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...