Question

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);
Was it helpful?

Solution

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

OTHER TIPS

You would do the same thing but in reverse.

For example, here you:

  1. Allocate space for the array
  2. Allocate space for each individual string

To free it, you do it in reverse:

  1. Free space for each individual string
  2. Free space for the array

the code would be

for (int counter = 0; counter < count; counter++)
{
free (arrayOfWords[counter].words);
}

free (arrayOfWords );

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top