Reputation: 115
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?
Upvotes: 1
Views: 813
Reputation: 81986
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.
Upvotes: 3
Reputation: 206707
According the draft standard,
18.6.1.2/9
void operator delete[](void* ptr) noexcept;
Effects: The deallocation function (3.7.4.2) called by the array form of a delete-expression to render the value of
ptr
invalid.
Hence, executing
delete [] a;
make a
invalid, according to the standard. If a certain platform allows a
to be used after that without crashing or other strange behavior is only a matter of luck.
Upvotes: 2
Reputation: 133609
You are not reallocating the array:
int *a = new int[n];
...
cin >> a[i]
...
delete [] a;
...
// here you must allocate a new array
...
cin >> a[i];
Once you delete the array, memory on heap that was available to is no longer available, you are storing data with your second cin
where you shouldn't. In your example this address 0x001172C8
becomes invalid after the delete. Allocating a new array should provide you a new address (usually).
Upvotes: 2