Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting elements of a dynamic array one-by-one

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

like image 675
Anmol Singh Jaggi Avatar asked Aug 02 '13 11:08

Anmol Singh Jaggi


People also ask

Can you delete an element from a dynamic array?

You can call delete on elements of dynamic array only if it is array of pointers or even Matrix of pointers.

How do you remove an element from a dynamic array in Java?

Delete an Element from a Dynamic Array If we want to remove an element from the array at the specified index, we use the removeAt(i) method. The method parses the index number of that element which we want to delete.


2 Answers

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;
like image 71
juanchopanza Avatar answered Oct 31 '22 19:10

juanchopanza


To delete

int *n=new int[2];

use

delete [] n;

the code

delete n;

is wrong when you allocate using new [].

like image 38
Minimus Heximus Avatar answered Oct 31 '22 19:10

Minimus Heximus