Search code examples
cpointersmallocfree

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

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

What am I doing wrong?


Solution

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