我玩了一点内存动态分配的游戏,但我不明白。在使用new语句分配一些内存时,我应该能够使用delete销毁指针所指向的内存。
但是当我尝试时,这个delete命令似乎不起作用,因为指针所指向的空间似乎没有被清空。
让我们以这段真正基本的代码为例:
#include <iostream>
using namespace std;
int main()
{
//I create a pointer-to-integer pTest, make it point to some new space,
// and fulfill this free space with a number;
int* pTest;
pTest = new int;
*(pTest) = 3;
cout << *(pTest) << endl;
// things are working well so far. Let's destroy this
// dynamically allocated space!
delete pTest;
//OK, now I guess the data pTest pointed to has been destroyed
cout << *(pTest) << endl; // Oh... Well, I was mistaking.
return 0;
} 有什么线索吗?
发布于 2010-07-19 19:25:21
这只是一个简单的例子来说明可能发生的事情,以及一些人提到的未定义的行为意味着什么。
如果我们在打印之前添加两行额外的代码:
delete pTest;
int *foo = new int;
*foo = 42;
cout << *pTest << endl;pTest的打印值很可能是3,就像您的例子一样。但是,打印值也可以是42。当pTest指针被删除时,它的内存被释放。正因为如此,foo指针有可能指向内存中pTest在被删除之前所指向的相同位置。
https://stackoverflow.com/questions/3280410
复制相似问题