0

I'm getting a strange problem in my unload() code, or more specifically the freeNode() recursive function that unload() calls.

I think I have the recursive part of the function nailed; once free(traversal) is called (on line 29) and then the function returns, going back to the previous 'level' of the trie. However, I have noticed that the node that has been free'd hasn't been free'd to NULL, but a garbage value. Can free() reset to NULL, or will I have to write code for that?

However, my more pertinent problem. When I run this code, it passes check50, and passes valgrind when passed a small dictionary (either the small one provided or another I created which contains the words 'can, cat, cats, da' (this helped me a bit more with understanding substrings and the layers), but fails when I pass it a larger dictionary. EDIT: I made a custom large dictionary with no apostrophes and it passes that fine, but it fails to unload words with apostrophe's properly.

Here's my code for unload():

Prototype in dictionary.h

bool freeNode(node* traversal);

Code in dictionary.c

bool unload(void)
{
    // set traversal node to root
    traversal = root;

    // return with the result of recursive function. True is successful, else false.
    return freeNode(traversal);
}

bool freeNode(node* traversal)
{    
    // loop over every node in the child array
    for (int i = 0; i < 27; i++)
    {
        // if the node exists, recursively call and keep traversing down
        if (traversal->child[i])
            freeNode(traversal->child[i]);

        // if we get to i == 26 and no deeper nodes have been found,
        // we need to free the current node and start again
        else if (traversal->child[i] == NULL && i == 26)
        {
            free(traversal);
            return true;
        }
    }
    return false;
}
0

With some help from Irene Naya on the CS50 facebook group, I was told that I should not be calling free(traversal) from within the loop. After taking it out of the loop and removing code that then became unnecessary, the problem was fixed!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .