Search code examples
c++arraysmemorydelete-operator

In C++, what happens when the delete operator is called?


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[3];
nums[0] = 1;
nums[1] = 2;

cout << "nums[0]: " << *nums << endl;
cout << "nums[1]: " << *(nums+1) << endl;

delete [] nums;

cout << "nums[0]: " << *nums << endl;
cout << "nums[1]: " << *(nums+1) << endl;

Solution

  • Two things happen when delete[] is called:

    1. 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
    2. 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).