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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With