释放内存导致分段错误 11

时间:2021-06-06 16:57:47

标签: c segmentation-fault malloc binary-search-tree free

我正在尝试创建一个二叉搜索树。这是我的节点初始化函数:

y

因为我正在分配内存,所以我知道我应该在其他地方释放它。我在我的主要方法中这样做:

node_t* node_init(int val){
        node_t* n1 = malloc(sizeof(node_t));
        n1->value = val;
        n1->leftNode = NULL;
        n1->rightNode = NULL;

        return n1;
}

然而,当我取消注释释放行时,我收到了分段错误错误。我不确定为什么会这样,因为一旦分配了内存,我就必须释放它。我没有在我的 int main(){ tree_t t1; tree_init(&t1); node_t* n1 = node_init(5); node_t* n2 = node_init(7); t1.count += add(n1, &(t1.root)); t1.count += add(n2, &(t1.root)); //free(n1); //free(n2); print_tree(t1.root); } 函数中进行任何释放,并且代码打印出一个没有 add 语句的有效二叉搜索树。

如果有帮助,这是我的添加功能:

free

1 个答案:

答案 0 :(得分:3)

对于初学者来说,函数 add 有未定义的行为,因为在某些执行路径中它什么都不返回。

你需要写

int add(node_t* n, node_t** tn){
        if(*tn == NULL){*tn = n; return 1;}
        if(n->value < (*tn)->value){ return add(n, &((*tn)->leftNode));}
        else if (n->value > (*tn)->value){ return add(n, &((*tn)->rightNode));}
        else{return 0;}
}

这些语句带有免费调用

    free(n1);
    free(n2);
    

不要在树中将 n1 和 n2 设置为 NULL。所以这个电话

    print_tree(t1.root);

调用未定义的行为。