简体   繁体   中英

Memory loss using valgrind in c

I have a custom struct mystruct.

typedef struct mystruct
{
    int data;
    struct mystruct * parent;
    struct mystruct * child;
    struct mystruct * next;
}mystruct;

Now I am doing postorder traversal of this mystruct in a function traverse()

mystruct * create(mystruct * root)
{
    mystruct * newNode=malloc(sizeof(mystruct));
    //change some pointers like make newNode->parent=root->parent
    //
    //
    return newNode;
}

void traverse(mystruct * root)
{
 if(root==NULL)
    return;

 //here I am calling a new function 
 if() // somecondition
 {
    mystruct * newNode=create(root);
    root=NULL;
    free(root);
    root=newNode;
 }


 traverse(root->child);
 traverse(root->next);

}

void delete(mystruct * root)
{
    if(root==NULL)
        return;

    delete(root->child);
    delete(root->next);
    free(root);
}

Even after freeing my structure at the end, valgrind shows memory loss due to newNode being created. How can I remove these memory losses?

It's not very clear without full valgrind output, but here:

root=NULL; free(root); root=newNode;

You assigned NULL to root, then you freeing NULL what is totally pointless, and assigning new pointer to root. So old value of root pointer is lost and you have no way to free that memory. Consider removing root=NULL .

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