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

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

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

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-02 18:44

    It's not necessarily a bad idea to allocate memory in a function. You just have to be sure to clean it up appropriately.

    The problem is that you might lose the ability to do that once you leave function scope.

    Just be careful with your design. Match up malloc with free every time and you won't have memory leaks.

提交回复
热议问题