In C++, I understand that the
delete operator, when used with an array, 'destroys' it, freeing the memory it used. But what happens when this is done?
I figured my program would just mark off the relevant part of the heap being freed for re-usage, and continue on.
But I noticed that also, the first element of the array is set to null, while the other elements are left unchanged. What purpose does this serve?
int * nums = new int; nums = 1; nums = 2; cout << "nums: " << *nums << endl; cout << "nums: " << *(nums+1) << endl; delete  nums; cout << "nums: " << *nums << endl; cout << "nums: " << *(nums+1) << endl;
Two things happen when
delete is called:
- If the array is of a type that has a nontrivial destructor, the destructor is called for each of the elements in the array, in reverse order
- The memory occupied by the array is released
Accessing the memory that the array occupied after calling
delete results in undefined behavior (that is, anything could happen--the data might still be there, or your program might crash when you try to read it, or something else far worse might happen).