0

my speller code works very well with all texts but when i ran valgrind there was heap leak in load() specifically in new_node malloc can you help me figure out why? there is my code for load() and unload()

bool load(const char *dictionary)
{


    FILE *dic = fopen(dictionary ,"r");
    if ( dic != NULL)
    {
        while( fscanf(dic, "%s" , wordy ) != EOF)
        {
            node *new_node = malloc(sizeof (node));

            if (new_node == NULL)
            {
                unload();
                return false;
            }

            strcpy (new_node ->word , wordy);

            //hashing
            int index = hash(new_node -> word);

            //inserting the new node in the link list
            new_node ->next = hashtable[index];
            hashtable[index] = new_node;

            //count number of words
            count ++;

        }

        fclose(dic);
        return true;
    }else
    {
    return false;
    }
}

unload code

bool unload(void)
{



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

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

}

1 Answer 1

2

Simply put, the unload function doesn't free anything. Worse, it loses the entire tree/trie. Here's why.

First, pointer is created and initialized and set to NULL.

Then the for loop starts. As the loop runs, each element in the hashtable array is set to NULL by this line: hashtable[i] = pointer;, losing track of the tree.

Finally, the while loop never starts because pointer always equals NULL. (If it had run, it would have generated a seg fault anyways because pointer->next doesn't exist because of the null.)

Is it possible that instead of hashtable[i] = pointer;, you meant to have pointer = hashtable[i];?

As for load, I didn't look at it, given the problems with unload. However, it's possible that load is ok (or maybe not). Keep in mind that valgrind is telling you that the memory that is leaked or lost is being allocated by the malloc in load. It's not necessarily saying that's the problem, just that this is where the memory is being allocated. It's giving a starting poing. Logically, that makes sense, since unload is where that memory would be freed.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • this was impressive .thank you ..i have just swiched hashtable[i]=pointer to pointer=hashtable[i] and it goes without any memory leak now :)) Commented Jan 10, 2018 at 20:48

You must log in to answer this question.

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