gpt4 book ai didi

c++ - C++ 中的越界数组访问和 reinterpret_cast

转载 作者:行者123 更新时间:2023-11-30 01:43:13 26 4
gpt4 key购买 nike

假设我有这样的代码

struct A {
int header;
unsigned char payload[1];
};

A* a = reinterpret_cast<A*>(new unsigned char[sizeof(A)+100]);

a->payload[50] = 42;

这是未定义的行为吗?创建指向 payload 外部的指针应该是未定义的 AFAIK,但我不确定在我在数组之后分配内存的情况下是否也是如此。

标准说 p[n]*(p+ n) 相同,并且“如果表达式 P 指向数组对象的第 i 个元素,表达式 (P)+N 指向数组的第 i+n 个元素”。在示例中,payload 指向分配了 new 的数组中的一个元素,所以这可能没问题。

如果可能的话,如果您的答案包含对 C++ 标准的引用就更好了。

最佳答案

所以 reinterpret_cast 未定义的行为,我们可以reinterpret_castcharunsigned char 我们永远不能 charunsigned char,如果我们这样做:

Accessing the object through the new pointer or reference invokes undefined behavior. This is known as the strict aliasing rule.

所以是的,这违反了严格的别名规则。

关于c++ - C++ 中的越界数组访问和 reinterpret_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38148270/

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