0

Please help me understand this:

  1. I have a pointer to a pointer

    char** word_array = NULL;
    
  2. Then I dynamically allocate memory in my code:

    n = 6;
    word_array = (char *) malloc(n* sizeof(char*));
    
  3. How do I delete all the memory allocated for the "array" of pointers? Is this call to free right?

    free(word_array);
    

    Or should I make a loop:

    for(int i = 0 ; i < n; i++) free(word_array + i);
    

1 Answers1

4

You used one malloc, so you should use one free.

Also the cast to char* is nonsense: word_array has type char**, not char*, and casting result of malloc() is discouraged.

So the entire flow will be like this:

int n;

char** word_array = NULL;

n = 6;
word_array = malloc(n* sizeof(char*));

if (word_array == NULL) {
    /* handle allocation error */
} else {
    /* do some work with word_array */

    /* free pointers stored in word_array if they are dynamically allocated
       and not freed yet */

    free(word_array);
}
klutt
  • 30,332
  • 17
  • 55
  • 95
MikeCAT
  • 73,922
  • 11
  • 45
  • 70