释放 C 中的链接结构

发布于 2024-10-28 00:19:19 字数 715 浏览 7 评论 0原文

好吧,我有一个仅使用 C 结构和指针构建的二叉搜索树,因为我疯了,不想使用 C++。无论如何,我遇到了一些严重的内存泄漏,因为我假设 free(tree),tree是下面结构的一个实例,并没有释放那棵树的所有孩子。

这是我的节点:

struct node{
    struct node* parent;
    struct node* left;
    struct node* right;
    int key; //the value of the node
};

这是我的 bst:

struct bst{
    struct node* root;
    int elements; //number of nodes in the bst
};

所以我的问题是,有没有比递归调用删除函数更好的方法?例如(当场写下):

void delete_tree(struct node* n){
    if(n == NULL) return;
    struct node* left = n->left;
    struct node* right = n->right;
    free(n);
    delete_tree(left);
    delete_tree(right);
}

Okay so I have a Binary Search Tree built using only C structs and pointers because I'm insane and didn't want to use C++. Anyways, I've got some serious memory leaks since I'm assuming free(tree), tree being an instance of the struct below, doesn't free all the children of that tree.

Here is my node:

struct node{
    struct node* parent;
    struct node* left;
    struct node* right;
    int key; //the value of the node
};

and here is my bst:

struct bst{
    struct node* root;
    int elements; //number of nodes in the bst
};

So my question, is there any better way of doing this than recursively calling a delete function? for instance (writing this on the spot):

void delete_tree(struct node* n){
    if(n == NULL) return;
    struct node* left = n->left;
    struct node* right = n->right;
    free(n);
    delete_tree(left);
    delete_tree(right);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拥抱影子 2024-11-04 00:19:19

我认为递归删除绝对没有问题。您可以使用迭代方法,但它不会有任何明显的好处,而且更难编写。

顺便说一句,您可以稍微简化代码并删除两个局部变量,如下所示:

void delete_tree(struct node* n){
    if(n == NULL) return;
    delete_tree(n->left);
    delete_tree(n->right);
    free(n);
}

I see absolutely nothing wrong with a recursive delete. You could use an iterative approach, but it wouldn't have any discernible benefits and would be harder to write.

By the way, you can simplify the code a little and remove the two local variables as so:

void delete_tree(struct node* n){
    if(n == NULL) return;
    delete_tree(n->left);
    delete_tree(n->right);
    free(n);
}
叹倦 2024-11-04 00:19:19

您正在进行递归调用,但从未真正调用free。您可能需要验证一个节点是否是叶节点(可能询问两个子节点是否都为空)并在该节点上调用free

You are making the recursive calls but never actually call free. You probably need to verify if a node is a leaf node (maybe asking if both children are null) and call free on that node.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文