fady fady - 4 days ago 5
C Question

error invalid pointer when i use free() to free a malloced pointer

i can't free this pointer after using it in my function.
it gives me this error msg. the function should check a trie dictionary for if a word is spelled right or wrong. and root is the first trie node.


Error in `./speller': free(): invalid pointer: 0x00007fe53a80d848


and here's the function:

bool check(const char *word)
{
int pos=0;
int path;
char wordChar=*(word+pos);
wordTriePtr cursor=(wordTriePtr) malloc(sizeof(wordTrie));
cursor=root;
while(wordChar!='\0')
{
path=determinePath(wordChar);
if(cursor->children[path]==NULL)
{
free(cursor);
return false;
}
else
cursor = cursor->children[path];

wordChar=*(word+(++pos));
}
if(cursor->isThisWord==true)
{
free(cursor);
return true;
}
else
{
free(cursor);
return false;
}
}


thanks in advance

Answer

Take a closer look at these two line:

wordTriePtr cursor=(wordTriePtr) malloc(sizeof(wordTrie));
cursor=root;

The first defines the variable cursor and initialize it to point to some memory you allocate.

The second line reassigns the variable, making it point somewhere else.

Further down in the loop you have

cursor = cursor->children[path]

which reassigns it again.

The reassignments are basically equivalent to

int a = 5;
a = 10;

and then wondering why a isn't equal to 5.

My guess is that you should not call malloc and free at all.