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
2 Answers 2
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;
-
Yes, but what was wrong in
delete (n+1)
? Aren't the individual memory blocks allocated withnew
only??!Anmol Singh Jaggi– Anmol Singh Jaggi2013年08月02日 12:00:31 +00:00Commented Aug 2, 2013 at 12:00 -
@AnmolSinghJaggi It is not allowed by the C++ standard.juanchopanza– juanchopanza2013年08月02日 12:01:19 +00:00Commented Aug 2, 2013 at 12:01
-
3@AnmolSinghJaggi the point is that
new []
allocates a whole array. It doesn't make sense to de-allocate single elements of the array. What could the OS possibly do with them?juanchopanza– juanchopanza2013年08月02日 12:10:55 +00:00Commented Aug 2, 2013 at 12:10
To delete
int *n=new int[2];
use
delete [] n;
the code
delete n;
is wrong when you allocate using new [].
Explore related questions
See similar questions with these tags.
std::vector
in this case) instead of dynamic arrays, and simply use the erase method of the container. But, on the other hand, what are you trying to do? Why you want to delete elements one-by-one?std::vectors
work under the hood ]std::vector::resize()
operation ]