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

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

    There are two basic types of memory you can work with in C. The two types are the stack and the heap. In general, the variables you create within a function will be allocated on the stack and will be freed when the function returns. Memory allocated in the heap will persist and you are obligated to manage that allocation within your program. Memory in the heap will remain allocated until you free is up using the pointer (memory address) that refers to the data block.

    A little reading on both will help you understand. I'd point out that you have two instances of fData, each with their own scope. Both pointers point to the memory you allocate with:

    char *fData = malloc (length2 * sizeof (char));
    

    .. even though they pass in and out of scope as your code executes.

提交回复
热议问题