Search code examples
cmallocfree

free variable when use malloc in c


char **loadValues()
{
    char **toReturn;
    int i;
    toReturn = malloc(5 * sizeof(char *));
    for (i = 0; i < 5; i++)
    {
        toReturn[i] = malloc(25);              //Change the size as per your need
        strncpy(toReturn[i], "string", i + 1); //Something to copy
    }
    return toReturn;
}

I copied above part of the code. In it, the "toReturn" variable is initialized by using malloc. Don't we have to "free" this "toReturn" variable?

Don't we have to free these variables when we return them in C. I still couldn't find a clear answer and I can't find a way to free it when I return it. Can someone explain it to me?


Solution

  • I assume that your question is: how does the function that calls loadValues and receives the pointer it returns, can free the loaded values.

    If we leave loadValues as it is now, the best solution is to create another function, called freeValues and call it when we are done with the values:

    void freeValues(char **values)
    {
        for (i = 0; i < 5; i++)
        {
            free(values[i]);
        }
        free(values);
    }
    

    Then you can do something like this in your main program:

    char **values = loadValues();
    // ... use values for something
    freeValues(values);
    

    Another option, is to allocate toReturn using a single call to malloc, in which case it can be freed simply by calling to free.