可能重複的:
C++ delete - It deletes my objects but I can still access the data?行爲刪除[]
我很好奇爲什麼我收到以下的(虛構的)代碼以下行爲。我使用在Ubuntu 10.10
#include <iostream>
int main(int argc, char *argv[])
{
int N = 5;
int *myarr = new int[N];//create an integer array of size 5
for (int i = 0; i < N; ++i)
{
myarr[i] = 45;
std::cout << myarr[i] << std::endl;
}
delete[] myarr;//kill the memory allocated by new
std::cout << "Let's see if the array was deleted and if we get a segfault \n" ;
for (int i = 0; i < N; ++i)
{
std::cout << myarr[i] << std::endl;
}
return 0;
}
代碼編譯,甚至與-Wall
標誌 GCC 4.4.5。輸出是
Desktop: ./a.out
45
45
45
45
45
Let's see if the array was deleted and if we get a segfault
0
0
45
45
45
Desktop:
怎麼會在myarr
陣列仍然可以就好像它是一個不段錯誤被徹底刪除訪問? 而且即使myarr
數組被刪除怎麼來的價值45似乎仍然在位置2,3正確打印和4
總之什麼是真正在這裏做delete[]
?