开发者

About Union's Unused Fields

Take this code snippet as example:

union stack {
    int a;
    float b;
};

union stack overflow;
overflow.a = 5;

When i do a printf("%d",overflow.b); i get zero on both gcc and turbo. When i do a printf("%f",overflow.b); i get zero on gc开发者_开发百科c and garbage on turbo.

Can you explain me why this happens. What exactly happens to the unused variables in a union?

Also if b is an int, printf("%d",overflow.b); gives value 5. Why is this?


In a union, all members share the same memory. When you assign to .a, you are writing an int value into the memory. When you access .b, you are interpreting those same bytes you just wrote an int into, as a float.

When the members are different sizes (as int and float might be), then some bytes will be changed while others are not. You may be accessing uninitialized memory when looking at the larger member.

There are no "unused variables", in a union, just unused interpretations of the common memory.

When you make b an int, you are saying that .a should interpret the bytes as an int, and that .b should also interpret the bytes as an int. In other words, it's useless to declare two members of the same union as the same type.


printf("%d",overflow.b); is UB(incorrect format specifier in printf).

printf("%f",overflow.b); is UB(overflow.b has not been assigned to). Both the members of the union share the same space. Both have different representations in memory(as one is int and another is float). Assigning to one and trying to access the second is definitely UB


If you've set a to something, part of b will be that, but part of b may be uninitialized data, depending on sizeof int and float on the system. Interpret that as a float, and who knows what will happen? Nasal demons. Don't do it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜