n元树结构的析构函数

Destructor of an n-ary tree struct

本文关键字:析构函数 结构      更新时间:2023-10-16

我有以下代码:

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;
}

这就是我尝试过的
我在编译/测试时没有遇到任何严重错误,但当我用Valgrind测试内存泄漏时,它表明我一直在进行内存泄漏。

我知道我的析构函数有很多缺陷;会有什么问题
提前谢谢!

内存泄漏是由您从未释放子级引起的
(将指针设置为NULL是不够的。)

你的析构函数可以这么简单:

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

内存泄漏的另一个原因也可能是递归生成或构造子节点。如果您在结构内部更改子数据字段,并以不同的方式管理它,比如在构造函数内部以某种方式携带它,或者在外部链接子字段和父字段,效果会更好。试试看,它可能会让你摆脱内存泄漏