Reputation: 959
I have looked through the other discussion and still cannot figure this out. I have a struct,
typedef struct { char * word; int count; } wordType;
In my code, I malloc each array[index].word and realloc the array of structs. How do I go about properly freeing them? I've included some snippets from my code for clarity.
wordType *arrayOfWords = NULL;
char temp[50];
arrayOfWords = realloc(arrayOfWords, (unique_words+1)*sizeof(wordType));
arrayOfWords[unique_words].count = 1;
arrayOfWords[unique_words].word = malloc(sizeof(char)*(strlen(temp)+1));
strcpy(arrayOfWords[unique_words].word, temp);
Upvotes: 0
Views: 171
Reputation: 3819
the code would be
for (int counter = 0; counter < count; counter++)
{
free (arrayOfWords[counter].words);
}free (arrayOfWords );
Upvotes: 0
Reputation:
You have to free each piece of allocated memory: i. e. the word
fields in all of the struct, then the arrayOfWords
array itself too:
for (int i = 0; i < NUM_WORDS; /* whatever it is */ i++) {
free(arrayOfWords[i].word);
}
free(arrayOfWords);
Some good advice: don't realloc()
in each and every step - it's tedious. Use an exponentially growing storage (double the space when it's exceeded).
Upvotes: 2
Reputation: 9930
You would do the same thing but in reverse.
For example, here you:
To free it, you do it in reverse:
Upvotes: 2