0

For pset6, in unload(), I'm attempting to free the trie like so:

**
* Frees the nodes
*/
void freeNode(node* ptr)
{
    for (int i = 0; i < 27; i++)
    {
        if ((ptr->next[i] != NULL) && ((ptr->next[i])->value == true))
            freeNode(ptr->next[i]);
    }
    free(ptr);
}

/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
    node* crawler = root;
    freeNode(crawler);
    if (root == NULL)
        return true;
    else
        return false;
}

But the code doesn't free any nodes, plus, along with a memory map, it throws this:

*** Error in `./speller': free(): invalid pointer: 0x0804b05c ***
======= Backtrace: =========
/lib/libc.so.6[0x4530dcf2]
./speller[0x80494d0]
./speller[0x804950a]
./speller[0x8048dc5]

I checked with GDB, 0x0804b05c is the pointer to the root node. Where does my code go wrong?

2
  • I'm not seeing any issue with your thought process, but why are you only freeing the subtries that are words? You should be freeing all subtries. Try removing && ((ptr->next[i])->value == true). Not sure it will help this issue, but will prevent some struggle later. Jul 23 '18 at 16:55
  • Also what's the output when you run valgrind? Or is it not compiling? Jul 23 '18 at 17:03
0

first question is where is root defined? Is it a global variable? node* crawler = root; sets crawler to root, but it is unclear as to where root is coming from.

Also, what is this: ptr->next[i]

I may be mistaken, but the ptr->next is a pointer, not an array, so what would ptr->next[15] actually mean? Also, I dont understand why you are recursively calling freeNode in the for loop. It actually is not freeing any nodes the way you have it setup. Notice that the free(ptr); actually is after the loop is done.

What you have to do to free the dictionary (I am assuming this is a hash table and linked list) is start at one bucket hash[0] which is the pointer to the head of that linked list, and keep track of the next pointer and free the pointer behind it. That way you can keep track of where you are in the linked list.

You must log in to answer this question.

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