deleting c++ array from heap and memory leak

Martin Broadhurst has already given the correct language-lawyer answer. I'm going to give the technical detail answer:

The point about using delete[] over delete is, that there is no way for the delete operator to know whether the passed pointer points to an array or to a single object. As such, delete only deletes a single object, while delete[] invokes some additional magic to recover the size of the array, and proceeds to delete all the elements.

Now deleting consists of two distinct parts:

  1. The objects must be destroyed by calling destructors. For an array, this means one destructor call for each array element.

  2. The memory that was used must be marked as free so that it may be reused. This is the job of the global operator delete() in C++. Since arrays are stored consecutively, this is a single call for the entire array.

valgrind is only concerned about memory. As such, it hooks memory allocating functions like malloc(), free(), operator new(), and operator delete().

What happens when you call delete instead of delete[] is, that the first object is destructed, and the pointer is passed on to operator delete(). operator delete() does not know about the object(s) that were stored inside the memory region, they are destroyed already anyway, so it will successfully mark the memory region as free. valgrind sees this operator delete() call, and is happy since all memory is free for reuse. However, your code failed to destruct all but the first array elements properly. And this is bad.


Calling delete on an array without using [] results in Undefined Behaviour. The Undefined Behaviour might be that the array is correctly deleted, which appears to be what you observed. You can't rely on this, however.