Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between new and new[1]?

What is difference between new and new[1]? Can I use delete with new[1]?

Edit

Well well well, I should've provided the background, sorry for that. I was evaluating BoundsChecker at work with VS 2010 and it complained about a memory leak when I used delete[] on new[1]. So in theory I know how the new and delete pair should be used but this particular situation confused me about the things under the hood. Any idea whats happening?

like image 933
Vishal Avatar asked Sep 22 '11 06:09

Vishal


2 Answers

Ed and aix are right, but there is much more going on underneath the hood.

If you use new, then delete, the delete call will execute one destructor.

If you use new[], you must use delete[], but how can delete[] know how much destructors to call? There might be an array of 2 instances, or one of 2000 instances? What some (possibly most or all) compilers do, is to store the number of instances right before the memory it returns to you.

So if you call new[5], then new will allocate memory like this:

+---+-----------+-----------+-----------+-----------+-----------+
| 5 | instance1 | instance2 | instance3 | instance4 | instance5 |
+---+-----------+-----------+-----------+-----------+-----------+

And you get a pointer back to instance1.

If you later call delete[], delete[] will use the number (in this case 5) to see how many destructors it needs to call before freeing the memory.

Notice that if you mix new with delete[], or new[] with delete, it can go horribly wrong, because the number might be missing, or the number might be incorrect.

If mixing new[1] with delete works, you might be just lucky, but don't rely on it.

like image 138
Patrick Avatar answered Sep 30 '22 22:09

Patrick


new creates an instance, whereas new[1] creates a single-element array. new[1] will almost certainly incur (small) memory overhead compared to new to store the size of the array. You can't use non-default constructors with new[].

new must be used with delete.

new[] must be used with delete[].

like image 26
NPE Avatar answered Sep 30 '22 23:09

NPE