union for uint32_t and uint8_t[4] undefined behavior? [duplicate]

耗尽温柔 提交于 2019-11-27 09:09:42
Joachim Isaksson

I don't know what means What's UB in C++ is to access inactive union members.

Basically what it means is that the only member you can read from a union without invoking undefined behavior is the last written one. In other words, if you write to addr32, you can only read from addr32, not addr8 and vice versa.

An example is also available here.

Edit: Since there has been much discussion if this is UB or not, consider the following (fully valid) C++11 example;

union olle {
    std::string str;
    std::wstring wstr;
};

Here you can definitely see that activating str and reading wstr may be a problem. You could see this as an extreme example since you even have to activate the member by doing a placement new, but the spec actually covers this case with no mention that it's to be considered a special case in other ways regarding active members.

[edit: read my edited section below, as I'm now unsure of whether this is undefined behavior or not; I'll leave the majority of my answer the same, however, until I can confirm further] Yes, this is undefined behavior. The C++ Standard, section 9.5.1, states:

In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time. [ Note: One special guarantee is made in order to simplify the use of unions: If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members; see 9.2. — end note ]

This means that only the most recently written to member can validly be read from as well (reading from the others is technically undefined behavior). Only one member of the union can be active at any time. Not two.

You might ask why? Consider your example. C++ does not mandate the endianness of addr32. It could be big-endian, little-endian, or middle-endian. If you write to addr8, and then read from addr32, C++ cannot guarantee you'll get the right value out because of the endianness in this case. One one computer, it could be one value, and on another, it could be a different value. Hence, doing so (that is, writing to one member and reading a different one) is undefined behavior.

Edit: For those wondering what "active" means, the MSDN documentation on Unions states:

The active member of a union is the one whose value was most recently set, and only that member has a valid value.

Edit Edit: I had always thought the behavior of doing this was undefined, but now I'm not so sure after R. Martinho Fernandes's comments and answer and after re-reading the quote from MSDN. The value is certainly unspecified/undefined, but now I'm not so sure if the behavior is (undefined value means you might get different results back; undefined behavior means your system might crash, the two being different things). I'm going to consider this further and talk with others I know to see if I can find a more explicit answer.

I do think it's safe to say, however, that in general reading an inactive member in a union can be undefined behavior (except for the special note in the Standard, of course), but I don't know if it always is (i.e. there may be some exceptions beyond the special note in the section of the C++ Standard I've quoted).

Basically because in C++ you are allowed to access just the active member of an union.

This means that if you set addr8 then you should access just that one until you set addr32, so that you can access it and so on. Setting one member to access data from another one is what should cause undefined behavior.

A member is considered active when you set it, and it remains so until another one becomes the active one.

Frankly, I can't find any mention in the standard that doing this is undefined behaviour. The standard does define the notion of "active member" for unions, but it doesn't seem to use that idea for anything other than explaining how to change the active member (§9.5p4), and to define constant expressions (§5.9p2). Specifically it doesn't seem to make explicit mention of validity of accessing either the active or the non-active members.

As far as I can see, something like the following can cause a strict aliasing violation, which is undefined behaviour:

union example0 {
    short some_other_view[sizeof(double)/sizeof(short)];
    double value;
};

This doesn't lead to strict aliasing violations because of some special rule for unions. It happens if you access the same memory location using types that can't be aliased, i.e., a "normal" strict aliasing violation.

But, since there's an exception for char when it comes to aliasing rules, the following does not lead to the same kind of violations:

union example1 {
    char byte_view[sizeof(double)];
    double value;
};

As far as I can see, there is nothing in the standard that leaves the following code with undefined behaviour:

example1 e;
e.value = 10.0;
std::out << e.byte_view[0];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!