How serious is the new / delete operator mismatch error?

I found the classic new / delete mismatch error in our code base as follows:

char *foo = new char[10]; // do something delete foo; // instead of delete[] foo; 

How serious is that? Does this cause a memory leak or error? What are the consequences. We have memory problems, but this does not seem serious enough to explain all our symptoms (a lot of corruption, etc.).

EDIT: Additional Questions for Clarity
Does it just free the first member of the array? or
Is the system losing control of the array because of this? or
Is corrupt memory a way?

+14
c ++ new-operator delete-operator
Feb 11 '12 at 8:00
source share
2 answers

This undefined behavior is serious (it can work, it can fall, it can do something else).

+16
Feb 11 2018-12-12T00
source share

At first glance, calling delete instead of delete[] should not be very bad: you destroy the first object and cause a memory leak.

BUT: then delete (or delete[] ) calls free to free memory. And free needs an initially allocated address in order to free memory correctly. Or the fact is that new returns the source address allocated by malloc, new[] returns a different address.

Calling the free address returned by new[] fails (it frees memory randomly).

See these very instructive links for a better understanding:

http://blogs.msdn.com/b/oldnewthing/archive/2004/02/03/66660.aspx#66782

http://web.archive.org/web/20080703153358/http://taossa.com/index.php/2007/01/03/attacking-delete-and-delete-in-c

From these articles it is also obvious why calling delete[] instead of deleting is also a very bad idea.

So, to answer: yes, this is a very serious mistake. It corrupts memory (after calling the destructor of only the first object).

+8
Sep 22 '14 at 20:41
source share



All Articles