简体   繁体   中英

valgrind shows unfreed memory

My code is:

bool check(const char* word)
{
    char letter;
    node* nodes = malloc(sizeof(node));
    for (int i = 0; isalpha(word[i]) != 0; i++)
    {   
        letter = tolower(word[i]);
        if (i == 0)
        {
            if (root->children[(int)letter - 96] == NULL)
                return false; 
            nodes = root->children[(int)letter - 96];
        }        
        else
        {
            if (nodes->children[(int)letter - 96] == NULL)
            {
               return false;
            }
            nodes = nodes->children[(int)letter - 96];
        }       
    } 
    if (nodes->value == 1)
        return true;
    else
        return false;    
    free (&letter);
    free (nodes->children);
    free (&nodes->value);
    free (nodes);
}

valgrind says that I don't free variable created in line 4, but I don't understand why, as I free it at the end.

These lines

if (nodes->value == 1)
    return true;
else 
    return false;  

ensure that the function returns before it can free any memory.

If a branch of your code returns from the function, the final free(nodes) won't be called, which is the case in your situation: you have multiple paths return true or return false .

In any case freeing a stack variable (as in free(&letter) ) doesn't make any sense and it's an error, since it's not dynamically allocated. This applies also to sub-objects.

The golden rule is that you need a free for each malloc/calloc , in your code you have 1 calloc and 4 free , which means that you are releasing memory for things that are not allocated on the heap ( nodes->children, &nodes->value, &letter )

Are you sure this code is properly formatted?

Not only does your function finish before the if (nodes->value)... , but also both of the branches return a value. That means you'd never progress from the if part to the free(...) statements.

Also you don't ever have to free local/stack values. free(&letter) is invalid and will likely cause a crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM