0

I solved every memory leak I had, but I'm having some issues with this one. What's a good method to free memory from node* checker in this case?

bool check(const char *word)
{
    node *checker = malloc(sizeof(node))  ;

    int position = hash(word) ;

    checker = table[position] ;

    while(checker != NULL)
    {

        if(strcasecmp(checker->word, word) == 0)

        {

            return true ;

        }

        checker = checker->next ;

    }

    free(checker);

    return false;
}

1 Answer 1

1

This is a common newbie error. The memory leak is happening because the memory is being allocated when checker is created, but is not used, and is abandoned soon after when another address is assigned to checker.

The code is both declaring checker and initilizing it by allocating memory for checker. Keep in mind that those are two different operations.

Since checker is essentially a placeholder used to walk the tree while searching for a word, there is no need to allocate memory to it. Instead, just set it to NULL when initializing. You're going to set it to existing memory addresses later.

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

1
  • Thank you so much Cliff! This lesson was so heavy, I started to code less than month ago with CS50. I've watched the shorts and readed the documentation dozens of times to finish this code, but when I got to the end, I almost had a brain overflow. Thanks for answering my first question ever! Jun 2, 2020 at 18:42

You must log in to answer this question.

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