简体   繁体   English

释放 memory 导致分段错误 11

[英]freeing memory causing segmentation fault 11

I'm trying to create a binary search tree.我正在尝试创建一个二叉搜索树。 This is my node initialization function:这是我的节点初始化 function:

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

        return n1;
}

Since I'm malloc'ing memory, I know I should be freeing it somewhere else.由于我正在 malloc'ing memory,我知道我应该在其他地方释放它。 I do so in my main method:我在我的主要方法中这样做:

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);
}

Yet, when I uncomment the freeing lines, I get a segmentation fault error.然而,当我取消注释释放行时,我得到一个分段错误错误。 I'm not sure why that Is the case since I must free the memory once it's been allocated.我不确定为什么会这样,因为一旦 memory 被分配,我必须释放它。 I don't do any freeing in my add function, and the code prints out a valid binary search tree without the free statements.我没有在我的add function 中做任何释放,并且代码打印出一个没有free语句的有效二叉搜索树。

If it helps, here is my add function:如果有帮助,这是我添加的 function:

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;}
}

For starters the function add has undefined behavior because in some paths of execution it returns nothing.对于初学者来说,function add 具有未定义的行为,因为在某些执行路径中它什么也不返回。

You need to write你需要写

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;}
}

These statements with calls of free这些带有免费调用的语句

    free(n1);
    free(n2);
    

do not set n1 and n2 to NULL in the tree.不要在树中将 n1 和 n2 设置为 NULL。 So this call所以这个电话

    print_tree(t1.root);

invokes undefined behavior.调用未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM