0

I've been stuck on a segmentation fault error occurring on my unload() function. Here's the relevant code:

bool unload(void)
{
    if (root != NULL)
    {
        printf("Address: %p\n", (node *)root) ;
        freemem(root) ;
    }
    return true ;
}

void freemem(node *current)
{
    // For each node, check if all children are NULL
    for (int i = 0; i<27; i++)
    {
        if (current->children[i] != NULL)
        {
            freemem(current->children[i]) ; 
        }
    }
    // If all children are pointing to NULL, free current node
    free(current) ;
    return ;
}

At if (current->children[i] != NULL) is where the segmentation fault occurs, and it occurs at the first iteration of the for loop; i.e., at i=0. Valgrind reports the following for that line.

==29979== Invalid read of size 8
==29979==    at 0x401488: freemem (dictionary.c:180)

Also, GDB shows that the address of the variable current doesn't match that of root at the point of the segmentation fault.

Any ideas what I'm doing wrong? Thank you!

4
  • 1
    If the address in current doesn't match root, it sounds like it is seg faulting in one of the recursions. Can you post the rest of freemem() please?
    – Cliff B
    Commented Aug 14, 2016 at 15:19
  • @Cliff B Thank you for helping me. I have edited my post to provide more information.
    – user571403
    Commented Aug 16, 2016 at 0:59
  • The code posted works fine when I plug it into my file. No seg faults, no memory leaks, nothing. Is it possible that you are freeing root elsewhere in the file? If you can't solve it from here, you will need to post the entire dictionary.c file, and any other files that have been changed.
    – Cliff B
    Commented Aug 16, 2016 at 1:46
  • You are right, @Cliff B! What happened was I had the global root node and the local current node for the load and check functions, which I freed before exiting these functions. It was the completely wrong thing to do. Code's working properly now. Thank you!
    – user571403
    Commented Aug 18, 2016 at 14:53

1 Answer 1

0

Answered in comments. Please accept this answer to remove from unanswered question pool.

The code posted works fine when I plug it into my file. No seg faults, no memory leaks, nothing. Is it possible that you are freeing root elsewhere in the file? If you can't solve it from here, you will need to post the entire dictionary.c file, and any other files that have been changed. – Cliff B 2 days ago

You are right, @Cliff B! What happened was I had the global root node and the local current node for the load and check functions, which I freed before exiting these functions. It was the completely wrong thing to do. Code's working properly now. Thank you! – user571403 6 hours ago

You must log in to answer this question.

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