gpt4 book ai didi

c - 获取超出范围的数组元素的地址是未定义的行为吗?

转载 作者:行者123 更新时间:2023-12-04 11:30:14 25 4
gpt4 key购买 nike

假设我们分配了一个包含 10 个元素的字节数组。定义了访问边界内的任何元素。

我了解越界读取和写入元素是未定义的行为。获取超出范围的数组元素的地址是未定义的行为吗?

例子:

#include <stdint.h>
#include <string.h>

int main(void)
{
uint8_t buf[10];
memset(buf, 0, sizeof(buf));

// Defined behavior
uint8_t a_value = buf[9];

// Defined behavior
buf[0] = 1;

// Undefined behavior?
uint8_t *addr = &buf[10];
}

最佳答案

&buf[10]是特例。您可以在没有 UB 的情况下获取数组的“最后一个元素”的地址。但是你不能走得更远或走在第一个元素之前。因此&buf[11]&buf[-1]是UB。

每个请求,来自 the latest available draft of C18 .

6.5.3.2/3 解释了 &buf[10]相当于 buf+10 :

Similarly, if the operand is the result of a [] operator, neither the & operator nor the unary * that is implied by the [] is evaluated and the result is as if the & operator were removed and the [] operator were changed to a + operator.



6.5.6/8 为我们提供了有关 + 行为的信息:

Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

关于c - 获取超出范围的数组元素的地址是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58862135/

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