Hello. This problem occured in a program that used dynamic memory, and the arrays were deleted and reallocated several times with varying length. It seemed to me that after deleting the arrays, the pointer is still pointing to some data with the same length. (And of course i didn't want it.) So i made a little program to see what delete[] does. I could not only read, but even write the deleted memory. (???)
Here is the test program:
#include <iostream>
using namespace std;
int main () {
int* a;
a = new int[30];
char pause;
for (int i=0; i<30; i++) a[i]=i;
cout << a[3] << '\n';
delete[] a;
cout << a[3] << '\n';
a[3]=9;
cout << a[3];
cin >> pause;
return 0; }
The program creates an array of 30 integers, and fills it with numbers. The array is then deleted by callling the delete[] operator. Finally i change the value of the already deleted data. The program writes the original value, the value after deletion and the value after modification.
The result: 3, -17891602 and 9 at debugging. ( 3 is the original value. At debug, when deleting an array, its content is automatically replaced by these -17891602 characters. 9 is the changed value.) At least after debug, i get a heap corruption error.
When i run the program without debugging: 3, 3 and 9. I get no errors. No exceptions, crash, an error message, nothing, like it's perfectly correct to modify unallocated memory.
The question: could anybody explain how exactly delete[] works, why doesn't it make the memory inaccessible and how i can prevent the program from accidentally using resources that already have been freed? (I use visual c++ 2008.)
Thank you!