gpt4 book ai didi

c - 关于指向 char 的通用指针和严格别名

转载 作者:行者123 更新时间:2023-12-04 05:33:06 25 4
gpt4 key购买 nike

我不知道为什么下面的代码工作正常,没有 gcc错误( -fstrict-aliasing -Wstrict-aliasing=1 )。

#include <stdio.h>

int
main(void)
{
char n = 42;
char *p = &n;
int *q = (int *)p;

*q = 10;

printf("%d|%d\n", *p, *q);

return 0;
}

如果我遵循严格的别名规则:

n1570, § 6.5 Expressions

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,

— a type that is the signed or unsigned type corresponding to the effective type of the object,

— a type that is the signed or unsigned type corresponding to a qualified version of 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

— a character type.



但是 *q没有与 *p 兼容的类型,要么是限定版本,要么是对应的有符号类型,要么是无符号类型,要么是字符类型。

那么,为什么允许呢?

最佳答案

这是不允许的。您发布的标准部分显示了您允许为对象设置别名的类型。

编译的代码并不意味着它是正确的。您的代码存在三个问题,导致程序表现出未定义的行为。

首先是您将 char 指针分配给 int 指针。
标准不强制它们的对齐和表示,因此结果指针无效。

int  *q = (int *)p;

然后你解释了 char n对象作为整数,违反了严格的别名。(请注意问题中标准的引用)。
*q;

最后你写了一个 int进入 char 对象的内存( char n ),这会导致溢出,因为 int 的大小总是大于 char 的大小.
*q = 10;

关于c - 关于指向 char 的通用指针和严格别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12337574/

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