Search code examples
cmallocfreedynamic-datarealloc

How to properly use free for specific struct type in C


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

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