我有下面的代碼,這是不正常...刪除[]功能是不是在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