PETROSCHOOL
PETROSCHOOL

Reputation: 25

How to free() the memory which is referenced by **pointer?

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);
    

Upvotes: 0

Views: 60

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

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);
}

Upvotes: 4

Related Questions