Why does free crash when called twice?

前端 未结 5 644
孤街浪徒
孤街浪徒 2020-12-09 09:20

In C and C++, free(my_pointer) crashes when it is called twice.

Why? There is bookkeeping of every malloc along with the size. When the f

5条回答
  •  借酒劲吻你
    2020-12-09 10:14

    You might be misinterpreting its behavior. If it crashes right away then it is implemented in a safe manner. I can attest that this was not common behavior for free() many moons ago. The typical CRT implementation back then did no checking at all. Fast and furious, it would simply corrupt the heap's internal structure, messing up the allocation chains.

    Without any diagnostic at all, the program would then misbehave or crash long after the heap corruption took place. Without having any hint why it misbehaved that way, the code that crashed wasn't actually responsible for the crash. A heisenbug, very difficult to troubleshoot.

    This is not common anymore for modern CRT or OS heap implementations. This kind of undefined behavior is very exploitable by malware. And it makes your life a wholeheckofalot easier, you'll quickly find the bug in your code. It has kept me out of trouble for the past few years, haven't had to debug untraceable heap corruption in a long time. Good Thing.

提交回复
热议问题