I have discovered the classic new/delete mismatch error in our codebase as follows:
char *foo = new char[10];
// do something
delete foo; // instead of delete[] foo;
Just how serious is this? Does it cause a memory leak or error? What are the consequences. We have some memory issues, but this doesn't seem serious enough to explain all our symptoms (heap corruption etc)
EDIT: extra questions for clarity
Does it just free the first member of the array? or
Does it make the system lose track of the array? or
Corrupt memory is some way?
It's undefined behavior serious (it could work, it could crash, it could do something else).
At the first sight, calling delete
instead of delete[]
should not be very bad: you destroy the first object and you provoke some memory leak.
BUT: then, delete
(or delete[]
) calls free
to free the memory. And free
needs its originally allocated address, to free the memory correctly. Or, the thing is, while new
returns the original adress allocated by malloc, new[]
returns a different address.
Calling free on the address returned by new[]
provokes a crash (it frees memory chaotically).
See these very instructive links for better understanding:
http://blogs.msdn.com/b/oldnewthing/archive/2004/02/03/66660.aspx#66782
From these articles it is also obvious why calling delete[]
instead of delete is also a very bad idea.
So, to answer: yes, it is a very very serious error. It corrupts memory (after calling the destructor of the first object only).
来源:https://stackoverflow.com/questions/9238731/how-serious-is-the-new-delete-operator-mismatch-error