0

I have been trying speller for far too long now and need help with unloading the dictionary.

This is the code I have now

// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
for (int x = 0; x < 25; x++)
{
    // Create new cursor
    node *cursor = hashtable[x];

    while (cursor != NULL)
    {
        cursor = cursor->next;
        free(hashtable[x]);
    }
}
return false;
}

If I understand correctly the response form this my code did nothing and makes no sense.

Asking for help...

==2804== 7,992,264 (1,456 direct, 7,990,808 indirect) bytes in 26 blocks are definitely lost in loss record 4 of 4

==2804== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)

==2804== by 0x40116C: load (dictionary.c:65)

==2804== by 0x400964: main (speller.c:40)

However it runs and instead of telling me I did not unload it says

double free or corruption (fasttop) Aborted

Can anyone give me some direction as how to fix my code?

1

Let's say the program loaded a dictionary of two words, "an" and "at". How many times will it try to free(hashtable[0])? By my accounting, twice, because the only node that gets free'd is hashtable[x].

in (crude) pseudocode for the above sample dictionary:

cursor points to node1
is cursornull? No, it points to node1
     setcursor to node2
    free(hashtable[0])
is cursor null? No, it points to node2
     set cursor to null
    free(hashtable[0])

and voilà, double free. You might find this walkthrough helpful.

Review the comment

// Unloads dictionary from memory, returning true if successful else false.

This unload function only ever returns false.

This loop for (int x = 0; x < 25; x++) is not going to free all elements of the hashtable. It is missing the last member (hashtable[25]).

2
  • Doesn’t the While (cursor != Null) mean that it will repeat the process of freeing until there is no words left in hashtable[0]?
    – Chris
    Dec 18 '19 at 18:45
  • added more info to the answer Dec 18 '19 at 19:10

You must log in to answer this question.

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