释放 C 中的链接结构
好吧,我有一个仅使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为递归删除绝对没有问题。您可以使用迭代方法,但它不会有任何明显的好处,而且更难编写。
顺便说一句,您可以稍微简化代码并删除两个局部变量,如下所示:
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:
您正在进行递归调用,但从未真正调用
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 callfree
on that node.