gpt4 book ai didi

c - 释放结构体指针,然后将其设置为 null,然后返回抛出错误

转载 作者:行者123 更新时间:2023-11-30 19:14:45 24 4
gpt4 key购买 nike

我在二叉搜索树中有一个删除节点函数,如下所示:

struct Node *_removeNode(struct Node *curr, TYPE val) {
/* FIX ME */
printf("curr->val: %.1f...%p\t val: %.1f\n", curr->val, curr, val);
struct Node* to_del = NULL;

if(val < curr->val){

return _removeNode(curr->left, val);

} else if( val > curr->val) {

return _removeNode(curr->right, val);

} else {

//case 1 -> curr is a leaf
if(curr->left == NULL && curr->right == NULL){
printf("removed %.1f\n", curr->val);
to_del = curr;
free(to_del);

}

//case if left node is not null but right is
if(curr->left != NULL && curr->right == NULL){
to_del = curr;
printf("to_del: %p...%.1f\t", to_del, to_del->val);
curr = curr->left;
printf("new curr: %p...%.1f\n", curr, curr->val);
free(to_del);

}

//case if right node is not null but left is
if(curr->left == NULL && curr->right != NULL){
to_del = curr;
printf("to_del: %p...%.1f\t", to_del, to_del->val);
curr = curr->right;
printf("new curr: %p...%.1f\n", curr, curr->val);
free(to_del);
}

//case both are not not null
if(curr->left != NULL && curr->right != NULL){
to_del = curr;
printf("to_del: %p...%.1f\t", to_del, to_del->val);
curr->right->left = curr->left;
curr = curr->right;
printf("new curr: %p...%.1f\n", curr, curr->val);
free(to_del);
}


}

to_del = NULL;
return to_del;

}

代码应该返回一个指向 NULL 的指针,以便通过测试用例,但我尝试的所有操作都会引发内存错误。有没有办法可以将结构设置为 NULL 然后返回它?

最佳答案

看:

    if(curr->left == NULL && curr->right == NULL){
to_del = curr;
free(to_del);
}
if(curr->left != NULL && curr->right == NULL){

如果第一个if为真,则curr指向的内存将被释放。然后,当您在第二个 if curr->left 中执行操作时,您会收到错误,因为不再有 ->left 了。

也许你应该使用else if

关于c - 释放结构体指针,然后将其设置为 null,然后返回抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33598205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com