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

后端 未结 7 2018
鱼传尺愫
鱼传尺愫 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

    Using malloc will allocate memory on the heap until it you free it.

    This means you need to assure every malloc has a corresponding free, also it is not implied that no other process can't access your data. It's just a value at an address.

    In your main you must free(fData) to avoid a memory leak.

    To sum up then:

    1) Your first assumption is correct, the second and third is not. It will stay allocated, but it's not local to the main, and not bound to the process as it terminates.

    2) Yes, you must free it

    3) Use the pointer you get from the function. If you do not return a pointer to your allocated data from a function, make sure that function frees it.

提交回复
热议问题