Reputation: 25
Please help me understand this:
I have a pointer to a pointer
char** word_array = NULL;
Then I dynamically allocate memory in my code:
n = 6;
word_array = (char *) malloc(n* sizeof(char*));
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
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