Why malloc memory in a function and free it outside is a bad idea?

前端 未结 5 713
傲寒
傲寒 2021-02-02 18:23

if this is a bad idea, how to allocate memory in the function?

5条回答
  •  佛祖请我去吃肉
    2021-02-02 19:03

    This question is easiest to answer if we reverse it:

    • Why might it be a good idea if every object malloc'd in a function is also freed in that same function?

    The answer is, there will be no memory leaks or dangling pointers, and this valuable outcome is achieved without cooperation of any other function. As a result, it is easier to get the code right, and the function has a simple interface.

    Now, what if a function calls malloc but not free? Then there have to be rules about who is obligated to free the memory, when this is permitted to be done, and when it is required to be done. These rules become part of the function's interface, and anybody calling the function must either ensure that the rules or followed, or possibly impose similar rules on its caller(s), and so on. Explicit memory management adds complexity to interfaces, and the more complex the interfaces, the easier it is to make a mistake that leads to a memory error—and in C, a memory error can make your program crash.

    Unfortunately, sometimes it is necessary to have an object that (a) must be allocated at run time and (b) must outlive the activation of the function that allocates it. In such cases, even though it seems like it might be a bad idea, we have no choice but to do the allocation, complicate the interface, and require the caller to manage the object correctly.

    (One of the simpler cases is when an object is allocated at run time but is permitted to live forever. But you must bound the number of such objects or you'll run out of space.)

提交回复
热议问题