gpt4 book ai didi

c - 以下 C union 访问模式是否未定义行为?

转载 作者:太空狗 更新时间:2023-10-29 17:06:35 24 4
gpt4 key购买 nike

以下不是现代 C 中的未定义行为:

union foo
{
int i;
float f;
};
union foo bar;
bar.f = 1.0f;
printf("%08x\n", bar.i);

并打印 1.0f 的十六进制表示。

但是以下是未定义的行为:

int x;
printf("%08x\n", x);

这个呢?

union xyzzy
{
char c;
int i;
};
union xyzzy plugh;

这应该是未定义的行为,因为 plugh 中没有成员已经写好了。

printf("%08x\n", plugh.i);

但是这个呢。这是未定义的行为吗?

plugh.c = 'A';
printf("%08x\n", plugh.i);

现在大多数 C 编译器都有 sizeof(char) < sizeof(int) , 与 sizeof(int)为 2 或 4。这意味着在这些情况下,最多 50% 或 25% 的 plugh.i将被写入,但读取剩余字节将读取未初始化的数据,因此应该是未定义的行为。在此基础上,整个读取是否为未定义行为?

最佳答案

Defect report 283: Accessing a non-current union member ("type punning")涵盖这一点并告诉我们如果存在陷阱表示则存在未定义的行为。

缺陷报告要求:

In the paragraph corresponding to 6.5.2.3#5, C89 contained this sentence:

With one exception, if a member of a union object is accessed after a value has been stored in a different member of the object, the behavior is implementation-defined.

与这句话相关的是这个脚注:

The "byte orders" for scalar types are invisible to isolated programs that do not indulge in type punning (for example, by assigning to one member of a union and inspecting the storage by accessing another member that is an appropriately sixed array of character type), but must be accounted for when conforming to externally imposed storage layouts.

C99 is 6.2.6.1#7中唯一对应的措辞:

When a value is stored in a member of an object of union type, the bytes of the object representation that do not correspond to that member but do correspond to other members take unspecified values, but the value of the union object shall not thereby become a trap representation.

C99 词是否具有相同的含义尚不完全清楚 含义为 C89 词。

缺陷报告添加了以下脚注:

Attach a new footnote 78a to the words "named member" in 6.5.2.3#3:

78a If the member used to access the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called "type punning"). This might be a trap representation.

C11 6.2.6.1 General告诉我们:

Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. If such a representation is produced by a side effect that modifies all or any part of the object by an lvalue expression that does not have character type, the behavior is undefined.50) Such a representation is called a trap representation.

关于c - 以下 C union 访问模式是否未定义行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52290456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com