簡體   English   中英

釋放 memory 導致分段錯誤 11

[英]freeing memory causing segmentation fault 11

我正在嘗試創建一個二叉搜索樹。 這是我的節點初始化 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;
}

由於我正在 malloc'ing memory,我知道我應該在其他地方釋放它。 我在我的主要方法中這樣做:

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

然而,當我取消注釋釋放行時,我得到一個分段錯誤錯誤。 我不確定為什么會這樣,因為一旦 memory 被分配,我必須釋放它。 我沒有在我的add function 中做任何釋放,並且代碼打印出一個沒有free語句的有效二叉搜索樹。

如果有幫助,這是我添加的 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;}
}

對於初學者來說,function 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);

調用未定義的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM