Reputation: 61
Here I want to extract words from 'text'
string. Dr. Memory says to me I have memory leak at line words = (char**) realloc(words, (amount + 1) * sizeof(char*));
What is the problem?
p = strtok(text, " ");
while(p != NULL) {
words = (char**) realloc(words, (amount + 1) * sizeof(char*));
words[amount] = strdup(p);
amount ++;
p = strtok(NULL, " ");
}
for(i = 0; i < amount; i ++) {
free(words[i]);
}
Upvotes: 1
Views: 1030
Reputation: 22094
Whn you use strdup
it will allocate a new string. So before you release the array, you need to free each string you allocated with strdup
.
You are not freeing the whole array though. The part you are allocating with realloc
.
So what is missing is a simple:
free(words);
Upvotes: 2