0

I've been slogging away at speller for about 2 weeks now and im tripping over the last hurdle.

heres what my check50 was spitting out

https://cs50.me/checks/41dd8b60a432fa6adcd672274f3452ba6eedfda3

so i added a second free(cursor); function to my unload and managed to get my check50 to look like this:

https://cs50.me/checks/8daedc705a824689c9f6c37558fc2407ffd17001

unload:

for (int i = 0; i < hashsize; i++)
{
    node *cursor = hashtable[i];

    while (cursor != NULL)
    {
        node *temp = cursor;
        cursor = cursor->next;
        free(temp);
        free(cursor);
        return true;
    }

}
return false;

i have no idea why adding that 2nd free(cursor) function worked but it did so now im left troubleshooting the last :( face.

when i run valgrind with

valgrind -v --leak-check=full --show-leak-kinds=all --track-origins=yes ./speller

it shows no memory leaks and my code runs fine in terms of finding the spelling errors when compared to the staff solution (albeit slower due to a basic hash function) but i have no idea which of the part of code is causing the issue. valgrind suggests that the error is with line 72:

node* new_node = malloc(sizeof(node));

but i dont really understand how that can be the case unless im not unloading the memory assigned here. the other two parts of my code can be found below. any help or advice would be greatly appreciated.

load:

FILE *fp = fopen(dictionary, "r");

if (fp == NULL)
{
    printf("Could not open dictionary. \n");
    return false;
}

char word [LENGTH + 1];
//SCANS FILE AND ASSIGNS ALL STRINGS DISCOVERED AS VARIABLE 'WORD'
while(fscanf(fp, "%s", word) != EOF)
{
    //ALLOCATE MEMORY FOR A NEW NODE
    node* new_node = malloc(sizeof(node));
    //MAKE NEXT POINT TO NULL
    new_node->next = NULL;
    if (new_node == NULL)
    {
        unload();
        return false;
    }

    //copies word into word part of node
    strcpy(new_node->word, word);
    //USE THE HASH FUNCTION TO GENERATE A NUMBER BASED ON THE FIRST LETTER OF EACH WORD //// 'H'
    int h = hashf(new_node->word);

    new_node->next = hashtable[h];
    hashtable[h] = new_node;

    wordcount++;
}

fclose(fp);
loaded = true;
return true;

check:

    int h = hashf(word);

node *cursor = hashtable[h];

while(cursor != NULL)
{
    if (strcasecmp(cursor->word, word) == 0)
    {
        return true;
    }
    cursor = cursor->next;
}
return false;
1

Do not access new_node->next before testing for new_node == NULL. If the first one hasn't segfaulted, the second one won't match.

Your error is related to the unload function. Your while loop will run at most once - after freeing exactly two memory blocks you return from the function. Move the return true; to after the outer loop, a return false; makes no sense here. And remove the free(cursor);.

You must log in to answer this question.

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