Removing dynamic array elements one by one

I want to delete a dynamically allocated array by going through all the elements and calling delete for each of them.
(I do this because I need to "move" the array to another location, that is, copy the original array and then delete it, but it will take 2x time than copying each element at once 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 get a segmentation error every time I run this ....

Although this works great -:

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

So, I assume that delete somehow deletes the whole array, not just one element!

Can someone explain if I guess correctly, and if so, suggest a possible workaround?

I am using GCC 4.7.3 on Ubuntu 13.04

+7
c ++ memory-management pointers dynamic-arrays
source share
2 answers

You cannot delete items individually. When you highlight new [] , you must free yourself with delete [] . What are you doing here:

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

it is not right. You invoke undefined behavior. It seems that he works by pure chance and cannot be relied on.

As for the workaround, it's not clear what the problem is, but if you want to “move” the array, you can simply assign it to another pointer:

 int* n=new int[2]; ... int* m = n; n = nullptr; .... delete [] m; 
+7
source share

To delete

 int *n=new int[2]; 

using

 delete [] n; 

the code

 delete n; 

incorrect if you highlight with new [].

+1
source share

All Articles