c++ - 引用未初始化的内存而不访问它是否合法?

标签 c++ variables memory

以下情况,我有一个包含指向整数变量的指针的结构,如下所示:

struct Structure[] = { 
    { &Var[0], &Var[1] },
    { &Var[2], &Var[3] }
};

事情是:Var 在第一次填充此结构时未初始化。 (如:NULL) 不久之后(第一次传递)变量 Var 将被初始化,并且引用将相应更新。

我认为这没有任何故障的原因,但我希望您能在这方面提供专业知识。 将无效内存(带有数组下标)的引用放入这样的数组中是否合法?还是我需要针对这种情况采取不同的方法?

在第一次初始化之前,我不会访问这些变量的内容。

非常感谢。

编辑: 为了以后读者的利益: Var 是一个全局指针变量,它在开始时被初始化为 NULL。初始化通过使用 new 将其变成一个数组。

最佳答案

我假设 Var 是一个指针对象,并且它的当前值是一个空指针。您的陈述暗示了这一点:

Var is uninitialized the first time this struct is filled. (As in: NULL)

我还假设 Var 没有在 block 范围内定义。如果它是在 block 范围内定义的,并且您没有对其进行初始化或为其分配值,那么它的值就是垃圾,不一定是空指针值,并且任何引用其值的尝试都有未定义的行为。

行为未定义。

如果 Var == NULL,则 &Var[N] 具有未定义的行为。

arr[index] 根据定义等价于 *(arr + index),所以 &Var[N] 等价于 >&(*(Var + N)).指针算术的行为是根据指针指向的数组对象的元素来定义的(单个对象被视为单元素数组),而空指针不指向任何东西。

题外话:

C 明确表示 &*x 被评估为 x,而 &[x[i]) 被评估为 x+i; C++ 没有这样说,所以 & 的操作数必须是有效的。 C++ 有一个添加 0 的特殊情况,即使对于空指针也有很好的定义(C 没有这种特殊情况)。但是 &Var[0] 在 C 和 C++ 中仍然无效,但原因不同。在 C 中,它等价于 Var + 0,但将 0 添加到空指针具有未定义的行为。在 C++ 中,它 not 等价于 Var + 0;而是等价于 &(*(Var + 0)); Var + 0 是一个空指针,解引用它有未定义的行为。)

题外话结束。

是的,只是计算一个无效地址具有未定义的行为,即使它从未被取消引用。

这是 2011 ISO C++ 标准 5.7 [expr.add] 第 5 段中的相关文本;特别注意最后:

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i + n-th and i − n-th elements of the array object, provided they exist. 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/18061394/

相关文章:

R 内存管理建议(插入符号、模型矩阵、数据框)

c++ - 如何存储大小位数组,例如大小 % 8 != 0?

c++ - 模板类成员函数的完美转发返回类型

c++ - 我的链接列表程序有效,但它不会显示所有列表

javascript - backbone 不能在定义后立即使用 this.el

javascript - 有没有办法从函数内定义的变量获取信息?

ios - 我应该在哪里使用 ARC 释放静态局部变量和全局变量?

java - C/C++程序可以调用mapreduce程序吗

c++ - typedef 持续多长时间?

Python 随机变量无法正常工作