简体   繁体   English

n元树结构的析构函数

[英]Destructor of an n-ary tree struct

I have the following code:我有以下代码:

const int MAXCHILD = 10;

struct Node {
    Node *child[10];

    Node();
    void deleteNode(Node *n);
    ~Node();
};

Node::Node() {
    for(int i=0; i<MAXCHILD; i++) {
        child[i] = NULL;
    }
}

void Node::deleteNode(Node *n) {
    if(n == NULL) {
        return;
    } else {
        for(int i=0; i<MAXCHILD; i++) {
            deleteNode(n->child[i]);
        }

        for(int i=0; i<MAXCHILD; i++) {
            n->child[i] = NULL;
        }
    }

    n = NULL;
}

Node::~Node() {
    Node *n = this;
    deleteNode(n);
}

int main() {
    Node *n = new Node();

    ...

    delete n;
    n = NULL;

    return 0;
}

This is what I've tried.这是我试过的。
I don't get any critical errors while compiling/testing but when I test for memory leaks with Valgrind, it shows I'm constantly making memory leaks.我在编译/测试时没有遇到任何严重错误,但是当我使用 Valgrind 测试内存泄漏时,它表明我一直在制造内存泄漏。

I'm aware there are many flaws in my destructor;我知道我的析构函数有很多缺陷; what would be the problem?会有什么问题?
Thank you in advance!先感谢您!

The memory leak is caused by your never deallocating the children.内存泄漏是由于您从不释放子项造成的。
(Setting the pointers to NULL isn't enough.) (将指针设置为NULL是不够的。)

Your destructor could be as simple as this:你的析构函数可以像这样简单:

Node::~Node() {
    for(int i=0; i<MAXCHILD; i++) {
        delete child[i];
        child[i] = nullptr;
    }
}

The other reason of memory leak also can be recursive generation or construction of children nodes.内存泄漏的另一个原因也可能是递归生成或构建子节点。 It will be better if you change child data field inside structure and manage it in a different way like carrying it somehow inside of the constructor or linking childs and parent externally.如果您更改结构内部的子数据字段并以不同的方式管理它会更好,例如以某种方式在构造函数内部携带它或在外部链接子项和父项。 Try it may be it will get you out of memory leak试试看它可能会让你摆脱内存泄漏

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

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