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

标签 c arrays undefined-behavior

假设我们分配了一个包含 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/

相关文章:

c++ - 是否定义了打印 NULL 字符串?

python - 支持函数嵌套定义的语言

javascript - PHP :How to convert array string of date to mysql date ( 27/1/2014 ) to ( 2014-01-27) before update in mysql

php - 从 PHP 脚本发送数组

java - 从堆创建 JTree

c++ - 未定义的行为是否适用于 asm 代码?

c - "signed or unsigned type"在此 C90 未定义行为定义中的含义是什么?

c++ - 用于开发 GUI 库的文章

c - 指针、引用、C

c++ - 常量算术的编译时评估是怎么回事,它可以在预处理器中完成吗?