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

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

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

5条回答
  •  误落风尘
    2021-02-02 19:05

    There are certain patterns to manage memory:

    1. to allocate the memory inside of the function, free it outside when it outlives due time
    2. to hold the pointer in the function where malloc is called, and free it after it is expired, as joveha said.

    Keep consistency in mind, or else it will easily lead to a memory leak or dangling pointers.

提交回复
热议问题