引用http://www.cplusplus.com/doc/tutorial/dynamic/ ,据说 new
运算符返回一个指针,指向分配的新内存块的开头。我们再假设任何一个指针都具有指针运算的特性,如果p
是一个指针,那么可以使得p + 1
指向内存中的下一个位置。
基于以上假设,我尝试了以下 block ,
#include <iostream>
using namespace std;
int main(){
int * ptr = (new int [4]) + 1;
ptr[3] = 2;
cout << ptr[3] << endl;
/*Before delete the dynamic allocated memory,
it should be necessary to let ptr point to the
beginning of it, add one line to do that:
--ptr;*/
delete [] ptr;
}
我预计 ptr[3]
应该超出新分配的内存范围。然而,结果仍然是2
。为什么指针运算变得无用?或者它真的是 new Type
返回一个 *Type
的对象吗?
感谢您的帮助。
最佳答案
I expected that
ptr[3]
should goes beyond the range of newly allocated memory.
确实如此。您需要注意不要这样做,因为(如您所注意到的)这是一个通常无法检测到的错误。动态分析工具,如 valgrind可以帮助诊断这些问题,但并不完美。
However, the result still give 2.
这意味着恰好有超出数组末尾的可访问内存,因此无法检测到无效访问。相反,它覆盖了不属于该数组的内存 - 也许它未被使用,或者您可能覆盖了一些其他数据,这将在以后导致莫名其妙的错误。
Why the pointer arithmetic become useless?
它与任何指针算法一样有用。指针算法无法检测数组的结尾,因此如果它超出范围,您将得到未定义的行为。
Or is it really
new Type
returns an object of*Type
?
new Type[]
返回指向分配数组的 Type*
指针。它的行为就像任何其他指针一样,因此添加一个会为您提供指向第二个元素的指针。
delete [] ptr
也给出了未定义的行为,因为 ptr
不再指向已分配数组的开头。
关于c++ - "(new Type [n]) + 1"返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21090132/