tags:

views:

161

answers:

3

I'm utilizing a library written by a collegue and discovered that valgrind was spewing out errors related to the delete.

The problem was that there were allocations of char arrays like

char* s = new char[n];

followed up later with delete s

instead of delete[] s

He tells me that the difference is really that delete[] s will call a destructor for the object at each position in s (if it has one), in this case it doesn't because it's a primitive type. I believe that is true.

So delete s is not really a bug as such and valgrind is just being very thorough.

Will it still definitely free all the memory associated with s?

+17  A: 

If you allocate an array using new[], you have to destroy it using delete[]. In general, the functions operator delete(void*) and operator delete[](void*) aren't guaranteed to be the same.

Refer here

Michael Williamson
I would change `new` to `new[]` to reduce confusion.
Billy ONeal
@Billy ONeal: Done, thanks.
Michael Williamson
@Michael: while you're fixing typos, I'm pretty sure you meant `operator delete` instead of `operation delete`.
Jerry Coffin
@Michael: +1 for fixing the answer.
Billy ONeal
+7  A: 

The standard says nothing about how the memory will get deleted -- it merely says that to not match the correct new with the correct delete is undefined behavior.

Actually, new[] followed by delete usually frees all the memory that was allocated with new[], but destructors for the items in that array are not called correctly. (Most of the time -- not that the standard mandates that)

Rather than dynamically allocated arrays, you should consider use of vector.

Billy ONeal
+1: `std::vector` (or possibly `std::string`) is almost certainly the better answer.
Jerry Coffin
It would be but this is a custom string class with no external dependencies. Done for compiled size reasons.
Matt H
@Matt H.: I seriously doubt you're going to beat `std::vector` for compiled size.
Billy ONeal
If there are destructors, `new[]` is all but guaranteed to return a pointer that does not point to an allocation block. `operator delete` might tolerate getting a pointer a few bytes into the block, or it might not.
Potatoswatter
@billy, as I've said, it's not my library. For good reason, the entire stdc++ was not allowed to be used in order to produce very small binaries.
Matt H
@Matt H: As I said, I seriously doubt you're going to beat std::vector with your own code. But good luck :)
Billy ONeal
+6  A: 

Forget about destructors. The difference between new/delete and new[]/delete[] is that these are two completely unrelated, independent memory allocation mechanisms. They cannot be mixed. Using delete to deallocate memory allocated with new[] is no different than using free for the same purpose.

AndreyT
+1 -- this is how you have to think about it, but in reality there's usually little difference in the allocated memory itself.
Billy ONeal