首页 > 解决方案 > 释放内存导致分段错误 11

问题描述

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

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语句的有效二叉搜索树。

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

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

标签: csegmentation-faultmallocbinary-search-treefree

解决方案


对于初学者,函数 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);

调用未定义的行为。


推荐阅读