Different ways to deallocate an array - c++

18,458

Solution 1

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.

Solution 2

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 [].

Solution 3

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**
Share:
18,458
AronAtVW
Author by

AronAtVW

Updated on June 04, 2022

Comments

  • AronAtVW
    AronAtVW almost 2 years

    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!