Possible Duplicate:
C++ delete - It deletes my objects but I can still access the data?
I am curious about why I am getting the following behaviour with the following (rather contrived) code. I am using gcc 4.4.5 on 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;
}
The code compiles even with -Wall
flag on. The output is
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:
How come the myarr
array can still be accessed as if it were ever deleted without a segfault?
Further even though the myarr
array was deleted how come the values 45 still seem to be printed correctly in positions 2,3 and 4.
In short what is delete[]
really doing here?