gpt4 book ai didi

c - 使用 union 在 C 中键入双关语

转载 作者:行者123 更新时间:2023-12-04 02:08:40 25 4
gpt4 key购买 nike

考虑以下代码:

union u{
int i;
long j[2];
};

int main(void){
union u *u = malloc(sizeof *u);
u->i = 10;
printf("%li\n", u->j[0]);
}

我想用 6.5解释代码的合法性:

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:

— a type compatible with the effective type of the object,

[...]

— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or



将此应用于上面的示例,我们有:
  • u->i = 10;u->i对象具有有效类型 int .
  • 左值 u有一个 union包含类型 int 的成员的类型.
  • 对象u->j[0]使用左值访问具有未指定的值 uunion u具有类型成员的类型 int .
  • 应用报价 6.5我们知道这里没有UB。

  • 问题:这样的推理正确吗?或者它包含一些错误?

    最佳答案

    是的,你的推理是正确的。这不是未定义的行为,而是根据 C11 第 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.



    第 3.19.3 节阐明了这意味着什么:

    unspecified value: valid value of the relevant type where this International Standard imposes no requirements on which value is chosen in any instance



    这是在 中提醒的附件 J:可移植性问题

    J.1 Unspecified behavior
    1 The following are unspecified:
    — ...
    — The value of padding bytes when storing values in structures or unions (6.2.6.1).
    — The values of bytes that correspond to union members other than the one last stored into (6.2.6.1).
    — ...



    J2 中未指定任何有关访问 union 成员的内容,这与未定义的行为有关

    话虽如此,可移植性问题可能很严重,因为第 6.2.6.1/6 节提醒:

    The value of a structure or union object is never a trap representation, even though the value of a member of the structure or union object may be a trap representation.



    陷阱表示是“不需要表示对象类型值的对象表示”(定义),可以理解为“获取陷阱表示 可能会执行陷阱 但不是必需的”(脚注) .所以访问非事件值可能会导致程序中断,但如果没有,只是没有保证。

    关于c - 使用 union 在 C 中键入双关语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59694057/

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