我有下面的代码,这是不正常...删除[]功能是不是在C++中正常工作
代码:使用delete[] p;
声明
#include <iostream>
#include <new>
#define nullptr NULL
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 == nullptr)
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 << p[n] << ", ";
delete[] p;
for (n=0; n<i; n++)
cout <<"a "<< p[n] << endl;
}
return 0;
}
后,当我打印的值p
所有元素都应该产生垃圾值,因为之前分配的内存被释放......但是,它仅为前2个元素产生垃圾值,其余元素打印分配给它的值...这意味着分配的内存总量为没有释放...
- 为什么发生这种情况?
- 这怎么解决?
未定义的行为是**未定义**。只是因为你释放了记忆并不意味着它必须用垃圾书写。事实上,由于你没有从段落中读取你不拥有的内存,所以很有可能是因为库存在内存中,以防你请求其他内容。更重要的是,你为什么将'nullptr'定义为'NULL'? – IllusiveBrian 2014-09-26 07:39:46
我会带着$ 200亚历克斯的未定义行为。 – user657267 2014-09-26 07:40:10
@KhairulBasar这些概念与已经存在范围的局部变量类似 - 您可能会发现阅读以下内容会有帮助:http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed -outside,其作用域 – 2014-09-26 07:50:58