Search code examples
cfunctionmemory-managementfreedynamic-memory-allocation

how to free an allocated array in a function in c


If we were to use malloc() in main(), we could free() that dynamic memory allocation in main().

However, if we use malloc() in a different function and we use that function in main(), where should we call free() to release the memory allocated in that function?

I.e., in the following source code:

#include <stdio.h>
#include <stdlib.h>

int * memory_allocate_function(int);

int main(void) {
    int n=5; //length of array, 5 for example.
    int *my_array;
    my_array = memory_allocate_function(n);
    return 0;
}

int * memory_allocate_function(int n) {
    int i;
    int *array;
    array=(int *)malloc(n * sizeof(int));
    if(array == NULL) {
        printf("can not allocate memory.");
        return NULL;
    }
    // I think i can't use "free(array);" in here.
    // Because I need that array in main().
    return array;
}

Is this the best way to do this?


Solution

  • Well after you are done working with it - free the dynamically allocated memory. But design wise - you can call the free in other function also to manage it properly. It really depends. There is no hard rule for that.

    For example here you should return that pointer to allocated memory and then after using it in main you can free it in main().

    So the structure would be something like

    int* memory_allocate_function(int n)
    {
        int i;
        int *array;
        array = malloc(n*sizeof(int));
        if(array == NULL)
        {
            printf("can not allocate memory.");
            exit(0);
        }
         return array;
    }
    

    Then in main()

    int main(void)
    {
        int n=5;    //length of array, 5 for example.
        int *arr = memory_allocate_function(n);
        // work with arr
        free(arr);
        return 0;
    }
    

    But yes name the function properly - if you are going to use the name memory_allocate_function function then do that only - not any other major logic should be there. This helps create a good readable code.


    Note one thing - here when you called the function and then you exited the function the only local variable that contains address of it, it's storage duration ended and you can never then access the memory you allocated. This is a case of memory leak. If you are determined that you won't return the pointer to memory from the function - then work with it (in the same function or different) and then free it (Before the scope of the function ends - notice not mentioning about where you would free it, you can do it in the same function and other function also).

    I can't help mentioning few things:- 1) Dont cast the return value of malloc. 2) Check the return value of malloc - in case it is NULL you would like to handle it separately. 3) The recommended signature of main() is int main(void)