gpt4 book ai didi

c - 这是严格的别名违规吗?

转载 作者:行者123 更新时间:2023-12-02 06:50:14 25 4
gpt4 key购买 nike

struct __packed element {
char val;
};

void foo(struct element arr[4], uint32_t a) {
uint32_t* i = (uint32_t*)arr;
*i = a;
}

int main(void) {
struct element arr[4] __aligned(4);

foo(arr, 5);
...
}

与标题差不多,这是 C 中的严格别名违规吗?

假设arr的存储类型是struct element[4]

最佳答案

是的,这 (*i = a) 是一个严格的别名冲突。

N1570 §6.5 p7:

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

  • 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.

以上要求都不满足:

  • uint32_t 与有效类型 char 不兼容。

  • 没有使用限定类型的char

  • uint32_t 不是 char 的无符号版本。

  • struct element 没有 uint32_t 成员。

  • uint32_t 不是字符类型。

如果原始数组的有效类型为 uint32_t 或使用 malloc 分配,有效类型发生在赋值时,这将是合法的。

uint32_t arr;
foo((struct element*)&arr, 5); // Possible pointer conversion issues still apply

void * arr = malloc(4);
foo(arr, 5);

注意 uint32_t* i = (uint32_t*)arr 也可能导致未定义的行为,如果转换后的地址不能存储在 uint32_t* 类型变量。但这是特定于实现的,因此取决于您的平台。

关于c - 这是严格的别名违规吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46886870/

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