Why exactly should I not call free() on variables not allocated by malloc()?

前端 未结 7 700
我寻月下人不归
我寻月下人不归 2020-12-01 17:32

I read somewhere that it is disastrous to use free to get rid of an object not created by calling malloc, is this true? why?

7条回答
  •  执念已碎
    2020-12-01 17:48

    It would certainly be possible for an implementation of malloc/free to keep a list of the memory blocks thats been allocated and in the case the user tries to free a block that isn't in this list do nothing.

    However since the standard says that this isn't a requirement most implementation will treat all pointers coming into free as valid.

提交回复
热议问题