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!

well one good practice to get into is to set your pointer to null after you delete it

int * a = new int[30];
delete [] a;
a = NULL;
//or
a = 0;

this will make sure the the pointer no longer points to where it used to and will also make it safe to delete again. with the delete function if you call it on a pointer you have already deleted than it will cause an error but calling delete is guaranteed to be safe. the delete function just frees the memory back up to the system. it doesn't actually delete the information in the memory.

wrong but I thought that may be Delete doesn't delete the data in terms of zeroing it. Instead, it flags the memory as deleted. The actual memory still holds data, the memory manager just knows now that it can overwrite it with new stuff.

Comments
agreed
This question has already been answered. Start a new discussion instead.