How serious is the new/delete operator mismatch error?

时光毁灭记忆、已成空白 提交于 2019-11-27 22:54:27

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

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

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