how to properly delete a pointer to array

It's:

delete[] foo;

Edit: Modern compilers really need you to use the correct delete operator, or they may leak memory or fail to run the proper destructors.

(I earlier stated that it didn't make a difference in practice. About 10 years ago, I tried many different compilers and failed to find one that actually leaked memory if you mistakenly omitted the []. However the howls of the mob - see below - have forced me to re-try my experimentation, and it seems that modern compilers/libc++s really do care.)


The requirement to match new[] with delete[] is technically correct.

Much better, however (at least in my opinion), would be to forget that you ever even heard of new[], and never use it again. I'm pretty sure it's been (at least) 10 years since the last time I used new[], and if I'd understood the situation very well, I'd have stopped even sooner than that. Pretty nearly any time you'd even consider using new[], an std::vector (or possibly std::deque) will be a better choice.

If you're trying to create something roughly equivalent to a vector or deque yourself, you don't normally want to use new[] for that either. They way they (at least normally, though it's possible to change this via a custom Allocator class) is to allocate "raw" storage with operator new (which is pretty much like malloc--you just give it a size, and it gives you that many bytes of storage). Then you use the placement new operator to create objects in that space, and explicitly invoke the object's destructor to destroy objects in that space.

To give one example, this is what allows std::vector to support reserve, which allows you to allocate extra space, which won't be turned into objects until you call something like push_back or emplace_back to create an actual object in the space you allocated.

When you use new[], it has to create objects of the specified type filling all the space you allocate. You can't create something like push_back that adds a new object to the collection, because the collection is always already "full". All you can do is allocate a new collection that's larger than the old one (so every addition to the collection is O(N) instead of the amortized O(1) supported by std::vector--a huge loss of efficiency).

Tags:

C++