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

后端 未结 7 2017
鱼传尺愫
鱼传尺愫 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:18
    1. Yes, memory allocated with malloc() stays until it is freed. How else could a function ever return variable-sized data to its caller?

    2. When a program exits, all the memory it allocated with malloc() is freed. However, it's generally not a good idea to keep lots of unneeded memory around until the program terminates, as it can impact performance, or the system can run out of virtual memory. This can be a particular concern for long-running programs, their memory use sometimes keeps growing until they use of all the available virtual memory.

    3. You call free() on the pointer returned by the function. So in your case, main() can do free(fData) after it's done using the array.

    This should all be covered in any C programming class or textbook.

    0 讨论(0)
提交回复
热议问题