gpt4 book ai didi

c - 抛弃 const 并读取值是 UB 吗?

转载 作者:太空狗 更新时间:2023-10-29 17:25:36 26 4
gpt4 key购买 nike

<分区>

澄清:我的问题是:

  • 使用 int 类型的左值访问有效类型 const int 的对象是否是 UB?

这个问题有两个代码示例,它们使用 int 类型的左值来访问有效类型 const int 的对象,我的目的是尽可能少地实现这一点尽可能分散注意力。如果除了这个特定问题之外还有任何其他 UB 来源,请发表评论,我会尝试更新代码示例。


下面给出具体的代码示例供讨论:

#include <stdio.h>
#include <stdlib.h>

int main()
{
const int c = 5;

printf("%d\n", *(int *)&c);
}

我认为它可能是 UB 的原因是严格的别名规则似乎说它是 UB:

C11 6.5/7

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,
  • a qualified version of a type compatible with the effective type of the object,
  • ...

此处对象的有效类型 (6.5/6) 是const int

第一个要点:intconst int 不是兼容类型(6.2.7/1、6.7.3/10)。

第二个要点:int 似乎不是const int 的限定版本,因为我们不是通过添加限定符来生成它的。然而 6.2.5/26 不清楚:

Each unqualified type has several qualified versions of its type, corresponding to the combinations of one, two, or all three of the const, volatile, and restrict qualifiers. The qualified or unqualified versions of a type are distinct types that belong to the same type category and have the same representation and alignment requirements. A derived type is not qualified by the qualifiers (if any) of the type from which it is derived.

它没有定义什么是“const int 的限定版本”,它只定义了应用于非限定类型时的术语“限定版本”。


第二个代码示例:

int *pc = malloc(sizeof *pc);
memcpy(pc, &c, sizeof c);
printf("%d\n", *pc); // UB?

由于 memcpy 保留有效类型 (6.5/6) ,通过 *pc 读取与通过 * 读取具有完全相同的严格别名规则交互(int *)&c 在第一个示例中执行。

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