Why does free crash when called twice?

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

    why does not it check second time when it may not found any allocated size for second free() call

    An additional check in the free() function itself would slow your program down in all correct cases. You should not be doing a double free. Managing memory is your responsibility as a programmer; failure to do so is a programming error. It's part of the philosophy of C: it gives you all the power you need, but as a consequence, makes it easy to shoot yourself in the foot.

    Many C runtimes will do some checking in their debug versions, so you'll get a reasonable notification in case you're doing something wrong.

提交回复
热议问题