AronAtVW
AronAtVW

Reputation: 115

Different ways to deallocate an array - c++

If you have said

int *arr = new int[5];

What is the difference between

delete arr;

and

delete [] arr;

I ask this because I was trying to deallocate memory of a 2d array and

delete [][] arr; 

did not seem to work but

delete arr;

seemed to work fine

Thank you in advance!

Upvotes: 4

Views: 28762

Answers (4)

O'Neil
O'Neil

Reputation: 3849

new type requires delete
new type[size] requires delete []
Using one instead of the other is wrong.

Btw you should not use such raw pointers like this unless you have a very good reason. Use std::vector or std::array instead.

And 2D MxN arrays should generally be linearised into 1D M*N arrays, also using these containers.

Upvotes: 6

パスカル
パスカル

Reputation: 489

I assume you mean new int[5], and the same new for dynamic memory. Otherwise, you are using stack, not the heap, and delete is undefined

While delete arr may seem to work for a 2-d array, I believe that the standard requires the following:

delete [] arr
arr=nullptr

This is because memory allocated with new [] must be freed with delete [] and vice versa. Also, it is dangerous to leave dangling pointers, hence the final line

Upvotes: 0

If you have said

int arr[5];

What is the difference between

delete arr;

and

delete [] arr;

One has an extra pair of brackets in it. Both will probably crash and/or corrupt the heap. This is because arr is a local variable which can't be deleted - delete only works on things allocated with new.

delete [][] arr; is not valid syntax. For an array allocated with for example new int[2][2], use delete [].

Upvotes: 2

bashrc
bashrc

Reputation: 4835

Neither of the delete's is correct.

When you declare an array like this:

int arr[5];

The space is allocated on the stack. Memory allocated on the stack isn't cleaned by delete. It gets auto cleaned (Although clean is not the correct term technically) when the stack unrolls on exit of scope. (Check When is an object "out of scope"? )

If you declre your array like this:

int *arr = new int[5]; // new allocates memory on heap

You call

delete[] arr; // this takes care of cleaning up memmory on **heap**

Upvotes: 1

Related Questions