How serious is the new/delete operator mismatch error?

谁说我不能喝 提交于 2019-11-26 21:15:24

问题


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?


回答1:


It's undefined behavior serious (it could work, it could crash, it could do something else).




回答2:


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

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 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!