0

Valgrind tells me I have a leak with malloc'ed node below. However, when I try to free it (free(n);) at the bottom of my code, outside the while loop, the program won't run (it doesn't pass check50 anymore).

When I try to malloc outside the while loop and free at the end of the program, the program also won't run though it compiles.

Any help is appreciated.

bool load(const char *dictionary)
{
    // Open dictionary for reading
    FILE *file = fopen(dictionary, "r");
    if(!file)
    {
        return false;
    }
    node *n = NULL;
    char dictionaryword[LENGTH + 1];
    while (fscanf(file, "%s", dictionaryword) == 1)
    {
        n = malloc(sizeof(node)); 
        // Add scanned word to node element
        strcpy(n->word, dictionaryword);

        // Get hash
        int index = hash(&dictionaryword[0]);

        // Case one: at least one node in hash table at index
        if (table[index] != NULL)
        {
            node *tmp = table[index];
            table[index] = n;
            n->next = tmp;
            wordcount++;
        }
        // Case two: no node in hash table at index
        // Also add node to beginning of list
        if (table[index] == NULL) 
        {
            table[index] = n;
            wordcount++;
        }
        if (n == NULL)
        {
            free(n);
            return false;
        }
    }
    fclose(file);
    return true;
}
0

The purpose of the load() function is to get the words of the dictionary into the memory so you don't need to free any memory in that function. In the unload() function however you need to free() all the memory you reserved before in the load() function. You can do it by looping throughout the node tables and using the pointer node->next until you get until the end of each table. It is explained here: https://youtu.be/qkC4l0pUvCk?list=PLhQjrBD2T382T4b6jjwX_qbU23E_Unwcz

You must log in to answer this question.

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