访问二叉树左节点的指针时出现 SIGSEGV,即使该指针已初始化

use*_*796 4 c recursion reverse binary-tree function-definition

我正在尝试创建一个返回二叉树的镜像副本的函数。我所说的“镜像”是指一棵树,每个左节点作为其右节点,反之亦然。

我进行此练习的页面中的视觉示例。

The one on the left gets copied to resemble the one on the right. This is the code of the function, with the definition of the binary nodes and "insert node" function that I use:

typedef struct bNode {
    int data;
    struct bNode *left;
    struct bNode *right;
} bNode;
    
//  =============================================================
    
bNode* reverse_tree (bNode **tree) {
    bNode *copy = malloc(sizeof(bNode));
    copy->data = (*tree)->data;
    if (!((*tree)->right) && !((*tree)->left)){
        return copy;
    }
        
    copy->left = reverse_tree(&(*tree)->right);
    copy->right = reverse_tree(&(*tree)->left);
    return copy;
}
    
//  =============================================================
    
void insert(bNode **tree, int data) {
    bNode *temp, *previous, *current;

    if (*tree == NULL) {
        temp = (bNode *) malloc(sizeof (bNode));
        temp->data = data;
        temp->left = NULL;
        temp->right = NULL;
        *tree = temp;
        return;
    }

    if (data < (*tree)->data) {
        insert(&(*tree)->left, data);
    } else if (data > (*tree)->data) {
        insert(&(*tree)->right, data);
    }
}
Run Code Online (Sandbox Code Playgroud)

After some troubleshooting, one single layer of recursion works fine, but after that, the pointers break (that is, they point to an inaccessible part of memory), and the program receives a SIGSEGV Segmentation fault.

Why do I receive this SIGSEGV and how do I avoid it?

P.S I am quite inexperienced with pointers; I hope it's not too bad.

(左边的被复制以类似于右边的)

Vla*_*cow 5

至少有这个功能reverse_tree has a bug.

该 if 语句的子语句:

if (!((*tree)->right) && !((*tree)->left)){
    return copy;
}
Run Code Online (Sandbox Code Playgroud)

gets the control when the both pointers, right and left, are null pointers.

所以这段代码片段:

copy->left = reverse_tree(&(*tree)->right);
copy->right = reverse_tree(&(*tree)->left);
Run Code Online (Sandbox Code Playgroud)

当只有一个指针为空指针时可以获得控制权。

在这种情况下,在函数的下一个递归调用中,此语句:

copy->data = (*tree)->data;
Run Code Online (Sandbox Code Playgroud)

为传递的空指针调用未定义的行为。