可以在不取消引用的情况下增加指针仍然是段错误或具有其他(未)定义的肮脏吗?
Can incrementing a pointer without dereferencing still segfault or have other (un)defined nastiness?
我在网上找到的所有关于增加指针导致段错误的例子都涉及指针的取消引用——如果我只想增加它怎么办(例如在 for 循环的末尾)而且我不在乎它是否最终进入无效内存,因为我不会再使用它。例如,在这个程序中,我每次迭代只需要步进 4,但在最后一次迭代后我再也没有取消引用这些指针。
float* leftRowPointer, resultRowPointer;
// assume they were correctly initialized
for (unsigned int i = 0; i < 4; ++i, leftRowPointer += 4, resultRowPointer += 4) {
// do some stuff
}
我需要做这样的事情吗?
for (unsigned int i = 0; i < 4; ++i) {
// same stuff
if (i != 3) {
leftRowPointer += 4;
resultRowPointer += 4;
}
}
有没有更好的方法来完成我想做的事情?
当我自己尝试时,似乎没有什么不好的事情发生,但这并不能保证它总是有效,不幸的是我在工作中无法访问 Valgrind 或类似软件。
我们正在使用 C++11 标准,fwiw,我在那里找不到任何直接适用于此的东西,但我会第一个承认我不知道标准足够好,知道在哪里可以找到它。
如果仅仅为指针分配一个无效引用是一个问题,那么将一个指针初始化为 NULL
也是一个问题。所以你的具体问题的答案是 'no'.
第 5.7 节,"Additive operators",第 5 段指定了这一点 - 加法本身的结果是未定义的;即使您从不取消引用指针,该程序也无效。
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.
尽管允许发生段错误,但发生段错误的可能性很小,但它仍然未定义所有相关内容。
我在网上找到的所有关于增加指针导致段错误的例子都涉及指针的取消引用——如果我只想增加它怎么办(例如在 for 循环的末尾)而且我不在乎它是否最终进入无效内存,因为我不会再使用它。例如,在这个程序中,我每次迭代只需要步进 4,但在最后一次迭代后我再也没有取消引用这些指针。
float* leftRowPointer, resultRowPointer;
// assume they were correctly initialized
for (unsigned int i = 0; i < 4; ++i, leftRowPointer += 4, resultRowPointer += 4) {
// do some stuff
}
我需要做这样的事情吗?
for (unsigned int i = 0; i < 4; ++i) {
// same stuff
if (i != 3) {
leftRowPointer += 4;
resultRowPointer += 4;
}
}
有没有更好的方法来完成我想做的事情?
当我自己尝试时,似乎没有什么不好的事情发生,但这并不能保证它总是有效,不幸的是我在工作中无法访问 Valgrind 或类似软件。
我们正在使用 C++11 标准,fwiw,我在那里找不到任何直接适用于此的东西,但我会第一个承认我不知道标准足够好,知道在哪里可以找到它。
如果仅仅为指针分配一个无效引用是一个问题,那么将一个指针初始化为 NULL
也是一个问题。所以你的具体问题的答案是 'no'.
第 5.7 节,"Additive operators",第 5 段指定了这一点 - 加法本身的结果是未定义的;即使您从不取消引用指针,该程序也无效。
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.
尽管允许发生段错误,但发生段错误的可能性很小,但它仍然未定义所有相关内容。