Search code examples
c++new-operatordelete-operator

Why can't I reassign elements to an array that was deallocated with delete []?


I'm investigating the delete [] operator, and I was wondering this - Why can't I make another array elements assignment on that same pointer that I deleted earlier using the 'delete []' operator?

Here is what I was doing:

int *a = new int[n];
cout << "Enter array elements:" << endl;
for (int i = 0; i < n; i++)
    cin >> a[i];

cout << "a address: " << &a << " points to: " << a << endl;
cout << "a: "; printArray(a,n);

delete [] a; cout << "deletes a" << endl;

cout << "Enter new a elements:" << endl;
for (int i = 0; i < n; i++)
    cin >> a[i];

cout << "a address: " << &a << " points to: " << a << endl;
cout << "a: "; printArray(a,n);

And the output is:

Enter array elements: 1 1 1
a address: 0025FAAC points to: 001172C8
a: 1 1 1
deletes a
Enter new a elements: 2 2 2
a address: 0025FAAC points to: 001172C8
a: -572662307 -572662307 -572662307

What is the reason for this?


Solution

  • Doing this:

    int * x = new int[3];
    x[0] = 1;
    x[2] = 2;
    
    delete [] x;
    
    x[0] = 3; // <-- Undefined Behavior!
    

    Dereferencing a pointer that points to memory that you've deleted is undefined behavior.

    Continuing to use that pointer will cause your program to behave in undefined ways including possibly crashing or having any number of other issues.

    That being said, x is just a variable. So we can keep using the variable. We just can't continue to use what it pointed to. So let's look at some code to explain this:

    int * x = new int[3];
    x[0] = 1;
    x[2] = 2;
    
    delete [] x;
    x = NULL;
    
    x = new int[4];
    x[3] = 4; // <-- This is fine.