Does memory allocated in a function still stay allocated after the function returns?

后端 未结 7 2123
鱼传尺愫
鱼传尺愫 2021-02-04 06:57

For the code below: (1) \"main\" calls a function \"f1\". (2) function \"f1\" does some number crunching; creates an array of \"char\" with mal

7条回答
  •  半阙折子戏
    2021-02-04 07:04

    malloc allocates memory on heap and therefore this memory remains allocated until it is freed by free function or program terminate successfully.
    In your case you freed ftemp in f1 so it is no longer exist after function terminates. fdata is still on heap and it is accessible to main as you are returning pointer to that allocated location.

    Once main terminates successfully, memory pointed by fdata get freed.

    So, it's considered good to free memory as soon as you don't need it any more. There is no point in freeing blocks at the end of a program, because all of the program's space is given back to the system when the process terminates (considering modern operating systems).

提交回复
热议问题