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

后端 未结 7 2019
鱼传尺愫
鱼传尺愫 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 06:59

    I assume, although the function "f1" has terminated, the allocated char array still stays allocated until the main program terminates completely.

    True. Dynamically allocated memory has nothing to do with functions, it belongs to process.

    That is, the allocated memory still belongs to the main and no other process can access it from outside. Am I right?

    Memory doesn't belong to main() (intended as function) but to process itself (of which main() is just the entry point). In a system with memory protection (where each process is isolated from the others) it's not accessible from outside. You can, however, allocate it in a system specific way to share memory across processes.

    Do I have to free the array (allocated in "f1") before the program terminates (or does it get freed as soon as the main program terminates) ?

    Yes. Unallocated memory - in most systems - is automatically deallocated by Operating System when process terminates but this is system dependant. IMO even when OS does it you should always deallocate, using such automatic deallocation as a red flag (I forget that to deallocate, is it a bug? something I missed?). Moreover if f1 is invoked 1000 times it'll leak memory each time quickly eating all available memory. Think about a process in a server, it may (and should) be up and running for years.

    If the answer for the second question is "yes" then how do you free an array allocated in another function?

    It's nice when who allocates memory also frees it. If it's not possible then caller will become responsible for such memory. It's, for example, what strdup() does. In such case called function must return (somehow) a pointer to allocated memory (or an handle/token that can be used by another specialized function). For example:

    char* pBuffer = f1();
    // Use it
    free(pBuffer);
    

    Note that there are many many techniques if you want to hide such internal pointer. You may use a token (for example an integer, key in a dictionary), a typedef or an opaque type.

提交回复
热议问题