Search code examples
csegmentation-faultmallocbinary-search-treefree

freeing memory causing segmentation fault 11


I'm trying to create a binary search tree. This is my node initialization 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. 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. I don't do any freeing in my add function, and the code prints out a valid binary search tree without the free statements.

If it helps, here is my add 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;}
}

Solution

  • For starters the function add has undefined behavior because in some paths of execution it returns nothing.

    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. So this call

        print_tree(t1.root);
    

    invokes undefined behavior.