My title pretty much explains the problem. I can tell that the problem probably exists where I called free (marked in my code). Here's the code below:

bool unload(void)
    node* trav = head;
    bool break_cond = false;

    while (true)
        for (int i = 0, counter = 0; i < 27; i++) 
            if (trav -> children[i] == NULL)
                trav = trav -> children[i];

            if (counter == 26)
                for (int j = 0; j < 27; j++)
                    free(trav -> children[j]); // Potential problem area
                trav = head;
            if (head == NULL)
                break_cond = true;
        if (break_cond == true)
    return true;

You have a tree structure (yes, a trie, but that's more a variation), and I don't see how you intend to free all nodes.

One misconception you seem to have is that freeing something makes the pointer NULL (your head would never turn NULL with that code!)

The easiest way to visit all nodes is to use recursion, or another kind of stack. That would require a recursive method like (pseudo-code)

function recursive_unload(current_node)
    for all children of current_node
        if child exists, recursive_unload(child)

initially called with the root node.

I also hope your structure is correctly initialised (for example using calloc instead of malloc, or using a loop)?

  • It's an easy fix, but why should I use calloc over malloc? All memory I allocate will be rewritten anyway, so what's the point of first making it zero before use? That just sounds like an extra step that wastes valuable time for no reason to me.
    – Jason_V
    Jun 27 '17 at 21:43
  • 1
    calloc writes all zeroes, which means NULL in case of pointers and false in case of boolean, which is probably exactly what you would initialise them to manually. If you are going to write NULL/false anyway, it's shorter.
    – Blauelf
    Jun 28 '17 at 7:06

You must log in to answer this question.

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