Search code examples
cfree

Incompatible type for argument 1 of free


I am getting this error when I try to free an array of Tuples that I created.

Here is where the error occurs:

void free_freq_words(Tuple *freq_words, int num)
{
  int i;

  for (i = 0; i < num; i++)
  {
     free(freq_words[i].word);
     free(freq_words[i]); /******* error here *********/
  }
}

I created the tuple array like this:

Tuple *freq_words = (Tuple *) malloc(sizeof(Tuple) * num);

And here is how a Tuple is defined:

typedef struct Tuple
{
   int freq;
   char *word;
} Tuple;

Note that I am pretty sure I have to free word before I free the Tuple itself since I allocate space for each word:

freq_words[num - 1].word = (char *) malloc(sizeof(char) * strlen(word) + 1);

The error I get is with the second free:

fw.c: In function âfree_freq_wordsâ:
fw.c:164:7: error: incompatible type for argument 1 of âfreeâ
       free(freq_words[i]);
       ^
In file included from fw.c:3:0:
/usr/include/stdlib.h:482:13: note: expected âvoid *â but argument is of type âT
upleâ
 extern void free (void *__ptr) __THROW;

I tried to cast before I freed, but that didn't work:

fw.c: In function âfree_freq_wordsâ:
fw.c:164:7: error: cannot convert to a pointer type
   free((void *) freq_words[i]);

I have never gotten an error with free before, except when I have tried to free the same thing twice, so I'm not sure what to make of this. I googled around but I couldn't find much. How should I change my code so free works?


Solution

  • allocation is : Tuple *freq_words = (Tuple *) malloc(sizeof(Tuple) * num);

    de-allocation is : free(freq_words);