简体   繁体   English

在C中使用valgrind的内存丢失

[英]Memory loss using valgrind in c

I have a custom struct mystruct. 我有一个自定义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() 现在,我正在函数traverse()中对此mystruct进行事后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. 即使最后释放了我的结构, valgrind仍然显示由于创建了newNode而导致的内存丢失。 How can I remove these memory losses? 如何消除这些内存丢失?

It's not very clear without full valgrind output, but here: 没有完整的valgrind输出,不是很清楚,但是在这里:

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. 您将NULL分配给root,然后释放完全没有意义的NULL ,然后将新指针分配给root。 So old value of root pointer is lost and you have no way to free that memory. 因此,根指针的旧值丢失了,您无法释放该内存。 Consider removing root=NULL . 考虑删除root=NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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