Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating and freeing memory in a loop in C

I know there are a lot of answers about this topic here on StackOverflow, and they've been very helpful but I'm not sure about one thing. Let's say I have funcA and funcB:

char * funcA()
{
    char * arr = malloc(sizeof(char) * 20);

    //store data in arr...

    return arr;
}

void funcB()
{
    char * arr;
    while(up to some finite value)
    {
        arr = funcA();
        //do stuff with array

        /* Do I perform these two lines here every iteration?*/
        free(arr)
        arr = NULL;
    }

    /*Or do I perform it only once, at the end of the loop?*/
    free(arr)
    arr = NULL;
}

I'm thinking arr is supposed to be freed in each iteration. Or will each iteration just "overwrite" the data in arr, and thus making it safe to only call free at the end of the loop? What is the correct way of doing this? Thanks.

like image 343
David Velasquez Avatar asked Dec 02 '22 15:12

David Velasquez


1 Answers

You need to call free(arr) in the loop, otherwise you'll loose the pointer to arr and leak memory for each iteration of the loop.

like image 50
Scott Presnell Avatar answered Dec 05 '22 05:12

Scott Presnell