0

I am having problems implementing the unload function in speller. I am trying to do recursion but running into some issues. Here is unload with the function below that I am calling. I am getting the error * Error in `./speller': double free or corruption (!prev): 0x0000000001ad2010 * Please help with this.

bool unload(void)
{

    void erase(node* root);

    erase(root);

    if(root == NULL)
    {
        return true;
    }

    else return false;

}

void erase(node* trav)
{
   for(int i = 0; i < 27; i++)
   {
       if(trav->children[i] != NULL)
       {
           trav = trav->children[i];
           erase(trav);
       }
       free(trav);
   }

}
0

This is a very common problem. Look at the following code block:

   if(trav->children[i] != NULL)
   {
       trav = trav->children[i];
       erase(trav);

The code is recursively calling erase, but the problem is what happens on the return path. Let's trace what happens for a bit. Say that you are a few levels into the recursion. We'll call it level 3. Now, the child is not null, so the next two lines execute. trav, which was at level 3 is now assigned to its child, a member of level 4. erase is then called on level 4. For now, we can ignore any further recursions and look at what happens when the code comes back from this call. trav, which was trying to process level 3 elements is now set to level 4 as the code goes back and starts the next pass of the for loop. This means that the rest of level 3 is lost.

To fix this, don't assign the value of the child to trav. Instead, call erase using trav->children[].

Next, there's the bigger issue of the free statement. It's inside the for loop. How many times are you going to free it, and what happens if you free it before completing the for loop?

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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