【发布时间】:2018-11-13 10:23:23
【问题描述】:
我在这里进行动态内存分配。但问题是删除内存后,数据并没有从该块中删除。只有前两个块正在删除。 为什么?
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new (nothrow) int[i];
if (p == 0)
cout << "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout <<"Value= "<< p[n] << ",Address = "<<&p[n]<<endl;
delete p;
cout<<endl<<"After Deallocation"<<endl;
for (n=0; n<i; n++)
cout <<"Value= " <<p[n] << ",Address = "<<&p[n]<<endl;
}
return 0;
}
【问题讨论】:
-
只有前两个块被删除 -- 你对“删除”的定义是什么?记忆不会消失在一股烟雾中。那些地方会留下一些残余物,你不能仅仅通过检查来确定这些残余物的含义。
-
顺便说一句,删除数组,你应该调用
delete[] p。 -
我也用过但是没用
标签: c++ memory dynamic new-operator allocation