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

前端 未结 7 684
我寻月下人不归
我寻月下人不归 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:46

    Please have a look at what undefined behavior means. malloc() and free() on a conforming hosted C implementation are built to standards. The standards say the behavior of calling free() on a heap block that was not returned by malloc() (or something wrapping it, e.g. calloc()) is undefined.

    This means, it can do whatever you want it to do, provided that you make the necessary modifications to free() on your own. You won't break the standard by making the behavior of free() on blocks not allocated by malloc() consistent and even possibly useful.

    In fact, there could be platforms that (themselves) define this behavior. I don't know of any, but there could be some. There are several garbage collecting / logging malloc() implementations that might let it fail more gracefully while logging the event. But thats implementation , not standards defined behavior.

    Undefined simply means don't count on any kind of consistent behavior unless you implement it yourself without breaking any defined behavior. Finally, implementation defined does not always mean defined by the host system. Many programs link against (and ship) uclibc. In that case, the implementation is self contained, consistent and portable.

提交回复
热议问题