Why does free crash when called twice?

前端 未结 5 646
孤街浪徒
孤街浪徒 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:23

    Good question. As you note, malloc and free usually do some form of bookkeeping, often in the few bytes preceding the allocation. But think of it this way:

    1. Malloc some memory -- adds the bookkeeping data.
    2. Free it -- memory is returned to pool.
    3. You or someone else malloc's some more memory, which might or might not include or line up with the old allocation.
    4. You free the old pointer again.

    The heap (the code for malloc an free management) has at this point already lost track of and/or overwritten the bookkeeping data, because the memory has gone back to the heap!

    Hence the crashes. The only way of providing this would be remembering every allocation ever made in a database somewhere, which would grow unbounded. So they don't that. Instead, remember not to double-free. :)

提交回复
热议问题