Thong Ton
Thong Ton

Reputation: 11

Delete element of array type pointer cause error?

I have an example:

int* arr = new int[1];
//First Time
arr[0] = 5;
cout << &arr[0] << " " << arr[0] << endl;
delete &arr[0];
cout << &arr[0] << " " << arr[0] << endl;

//Second time
arr[0] = 5;
cout << &arr[0] << " " << arr[0] << endl;
delete &arr[0]; //Error from here
cout << &arr[0] << " " << arr[0] << endl;

The result from the code above:

00529EF0 5
00529EF0 -572662307
00529EF0 5
//Where the code stop

I don't know why it causes me the error? It doesn't let me delete arr[0] the second time, even though the first time successfully deleted and I assign a new value for it.

Upvotes: 1

Views: 248

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596332

Undefined Behavior.

&arr[0] is the same memory address that arr decays to. So you are really calling delete arr;. This is undefined behavior because you are using delete when you need to use delete[] instead. Memory allocated with new MUST be freed with delete. Memory allocated with new[] MUST be freed with delete[].

But, lets assume your compiler's runtime has enough info in the allocated array's metadata to free the array correctly. delete'ing an array free the entire array. You can't free individual elements of the array. And accessing any element of of array after freeing the entire array is undefined behavior. You are accessing arr[0] after calling delete arr; to free the array. You are not allocating a new array for arr to point at. You are lucky your code did not just crash outright.

That is the definition of undefined behavior - ANYTHING could happen. You might read the old memory before it is overwritten. You could read from random memory. You could corrupt memory. You could crash.

Upvotes: 1

eesiraed
eesiraed

Reputation: 4654

If you dynamically allocate an array with new[], you have to delete it with delete[], which will free the entire array. You can't free individual elements. Your code has undefined behavior because you used delete instead of delete[], so anything can happen. Just because it appeared to work doesn't mean it's correct.

Upvotes: 4

Related Questions