Search code examples
cgarbage-collectionfree

Allocated memory for returning values in C


If the return value of a function, say, myFunc, is an allocated space. Does the parent function still need to free that part of the memory?

For example:

char * myFunc() {
    return malloc(5);

    // free() not called
}

int main() {
    char * str = myFunc();

    // does str need to be freed?
    return 0;
}

Solution

  • To free() or not to free()?

    When a process terminates, all of its memory is returned to the system, including heap memory allocated by functions in the malloc package. In programs that allocate memory and continue using it until program termination, it is common to omit calls to free(), relying on this behavior to automatically free the memory. This can be especially useful in programs that allocate many blocks of memory, since adding multiple calls to free() could be expensive in terms of CPU time, as well as perhaps being complicated to code. Although relying on process termination to automatically free memory is acceptable for many programs, there are a couple of reasons why it can be desirable to explicitly free all allocated memory:

    􏰀 1. Explicitly calling free() may make the program more readable and maintainable in the face of future modifications.

    􏰀 2. If we are using a malloc debugging library to find memory leaks in a program, then any memory that is not explicitly freed will be reported as a memory leak. This can complicate the task of finding real memory leaks.

    3. To avoid memory leak.