Islam Talhi
Islam Talhi

Reputation: 35

How to free dynamically allocated array in C in a for loop

So this is the code I have: my main function calls the readtitles function

int main() {
   char **bookTitles;
   bookTitles= malloc(bookCount * sizeof(char*));
   readtitles(bookTitles,  bookCount);

   free(bookTitles);
   return 0;
}

and this is my readtitles function:

void readtitles(char **bookTitles, int bookCount) {

    int i;

    printf("Enter the book titles: ");

    for(i = 0; i < bookCount; ++i) {
        *(bookTitles+i) = malloc(61*sizeof(char));
        scanf(" %[^\n]",*(bookTitles+i));
    }
}

when I use valgrind I get memory leaks how do I go about freeing the memory in a for loop?

Upvotes: 0

Views: 535

Answers (1)

S.S. Anne
S.S. Anne

Reputation: 15566

You loop over the array and free it. After that, you can free the array of pointers:

int i;
for( i = 0; i < bookCount; i++ )
    free(bookTitles[i]);
free(bookTitles);

Upvotes: 3

Related Questions