0

few people suggested to use a recursive method of unloading a Trie data structure, but I am struggling with it a bit.

I am stuck on the part on how can I update the root node ( the main node which holds all the data) while calling function multiple times, because it seems that it creates a copy each time I run it and because of that I am geting this:

* Error in `./speller': double free or corruption (top): 0x0000000002131ac0 * Aborted

How can I pass the root node so it updates correctly instead of the local copy?

My code:

Unload node - recursive function ( atleast that's that I think it is )

int un_node(node * temp)
{
   // Bool used to detect if we can move to a lower level.
   bool w_found_now = false;

   for (int t = 0;t < 27;t++)
   {
      if ( temp->children[t] != NULL)
      {
          w_found_now = true;
          temp = temp->children[t];
          break;
      }
   }
   // If we can't, that means we reached the BOTTOM node,
   // so we need to free it and start from the TOP again.

   // If we detected a children, call the function again
   // from it's position.
   if ( w_found_now == false )
   {
      free(temp);
      un_node(root);
   }
   else if ( w_found_now == true  )
   {
      un_node(temp);
   }

   // If all nodes are fred, return 0 and end this function.
   return 0;
}

I am starting this 'loop' via:

bool unload(void)
{        
    un_node(root);

    return true;
}
0

The better question is why do you need to update the root node? Or why do you need to update any data when you're freeing everything?

The method is to check if a node has a child. If it does, recursively call and move into that function. When there's no child, delete the node and return to the prior call. On return, that prior node remembers where it was and when all the children are checked and cleared, it will then delete the current node.

   for (int t = 0;t < 27;t++)
   {
      if ( temp->children[t] != NULL)
      {
          un_node( temp->children[t]);
      }
   }
   free(temp);
   return 0;

I also don't know why it returns an int. Since the return value isn't being used for anything, it could be a void.

If you don't follow, try reaching out on one of the other forums where you can chat with someone. (I hang out on Slack.)

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

1
  • Thank you Sir, it does work, but could explain a little bit about it? – Gintas Jul 27 '18 at 12:24

You must log in to answer this question.

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