Deleting elements of a dynamic array one-by-one

Anmol Singh Jaggi picture Anmol Singh Jaggi · Aug 2, 2013 · Viewed 8.2k times · Source

I want to delete a dynamically-allocated array by looping through all the elements and calling delete on each of them.
(I am doing this because I have to "move" an array to another location, that is, to copy the original array and then delete it, but that would take 2x the time than simultaneously copying each element and calling delete on them individually)

I have the following code:

int main()
{
    int *n=new int[2];
    delete n;
    delete (n+1);
}  

But i am getting a Segmentation error each time i run this....

Although, this works fine -:

int main()
{
    int *n=new int[1];
    delete n;
}    

So, my guess is that delete is somehow deleting the whole array instead of a single element!

Could anyone please explain if my guess is right, and if it is, suggest a possible workaround?

I am using GCC 4.7.3 on Ubuntu 13.04

Answer

juanchopanza picture juanchopanza · Aug 2, 2013

You cannot delete the elements individually. When you allocate with new [] you must deallocate with delete []. What you are doing here:

int *n=new int[1];
delete n;  // ERROR: should be delete []

it not correct. You are invoking undefined behaviour. It seems to work by pure chance and cannot be relied on.

As for a workaround, it isn't clear what the problem is, but if you want to "move" the array, you could just assign it to a different pointer:

int* n=new int[2];
...
int* m = n;
n = nullptr;
....
delete [] m;