0

My unload function:

void clean(node* trav){
    //Iterate over the trie structure
    for(int i=0; i<CHILDREN_LENGTH; i++){
        //Recursively delete deeper nodes if curent node is not null
        if(trav->children[i] != NULL)
            clean(trav->children[i]);
    }
    //Free up memory
    free(trav);
}

/**
 * Unloads dictionary from memory. Returns true if successful else false.
 */
bool unload(void)
{
    // TODO
    clean(root); //Delete the trie
    fclose(dict); //Close the dictionary
    return true;
}

And my valgrind leak summary

==6368== LEAK SUMMARY:
==6368==    definitely lost: 1,916,768 bytes in 8,557 blocks
==6368==    indirectly lost: 1,948,352 bytes in 8,698 blocks
==6368==      possibly lost: 0 bytes in 0 blocks
==6368==    still reachable: 0 bytes in 0 blocks
==6368==         suppressed: 0 bytes in 0 blocks

I am positive that the unload function does free up some memory as, without it, this is my valgrind leak summary

==6567== LEAK SUMMARY:
==6567==    definitely lost: 1,916,768 bytes in 8,557 blocks
==6567==    indirectly lost: 1,948,352 bytes in 8,698 blocks
==6567==      possibly lost: 0 bytes in 0 blocks
==6567==    still reachable: 78,361,248 bytes in 349,827 blocks
==6567==         suppressed: 0 bytes in 0 blocks

I am not able to trace back to where exactly the other bits of memory is lost.

Here is the full code if needed https://gist.github.com/lPing7/0b3182efbd1b40b9192156517899a6fc

1

fclose the dict at the end of load, the file should be open only for the duration of reading. Otherwise, unload looks fine.

In your hash function

    return (c != '\'')? c - 'a' : CHILDREN_LENGTH;

should be

    return (c != '\'')? c - 'a' : CHILDREN_LENGTH - 1;

because CHILDREN_LENGTH - 1 is the highest index in an array of length CHILDREN_LENGTH.

Then there's another problem whenever you allocate memory using malloc. This memory block initially has an undefined content (for short tests often all-zeroes, but no guarantee on that). Either after each malloc initialise the struct (setting the boolean to false and all the pointers to NULL), or use calloc(1, sizeof(node)) instead of malloc(sizeof(node)). This zeroes the memory, which means false for booleans and NULL for pointers.

A small vulnerability that might not have consequences for the sample dicts: What would happen if the file did not end in a newline?

2
  • Thanks, using calloc and fixing the hash function did the trick. About that vulnerability, I'm guessing we would not store the last word of the dictionary in our data structure. Is that right? @Blauelf Apr 12 '17 at 11:29
  • That would be harmless. If a word ended at the end of file instead of a newline, your inner loop would keep looping forever, since c never becomes '\n'.
    – Blauelf
    Apr 12 '17 at 11:39

You must log in to answer this question.

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