为什么在这段代码中出现分段错误?

时间:2019-05-16 03:20:03

标签: c pointers tree segmentation-fault

我正在使用C构建树,并且从addNode()函数中遇到了分段错误。

我怀疑这是因为我正在将一个孩子分配给NULL指针,但事实并非如此。

//This is the tree node struct.
struct NODE {
    int value;
    struct NODE* child_list;
    struct NODE* right_sibling;
    struct NODE* parent;
};


//This function adds a node to an element in the tree with a value equal to parent value.
struct NODE* addNode (struct NODE* existing, int parentVal, int childVal) {
    struct NODE* child = existing;
    struct NODE* child_right = child->right_sibling;

    while (child != NULL) {
        if (child->value == parentVal) {
            struct NODE* new = malloc(sizeof(struct NODE));
            new->value = childVal;
            new->parent = child;
            new->right_sibling = child->child_list;
            child->child_list = new;

            break;
        }
        while (child_right != NULL) {
            if (child_right->value == parentVal) {
                struct NODE* new_sibling = malloc(sizeof(struct NODE));
                new_sibling->value = childVal;
                new_sibling->parent = child_right;
                new_sibling->right_sibling = child->child_list;
                child_right->child_list = new_sibling;
                break;
            }
            child_right = child_right->right_sibling;
        }
        child = child->child_list;
    }


    return existing;
}

//Here is the implementation of the function that I used to test the function.

int main () {

    struct NODE* root = malloc(sizeof(struct NODE));
    root->value = 100;
    root->child_list = NULL;
    root->right_sibling = NULL;
    root->parent = NULL;

    root = addNode(root, 100, 7);
    root = addNode(root, 100, 10);
    root = addNode(root, 100, 15);
    root = addNode(root, 7, 30);
    root = addNode(root, 15, 20);
    root = addNode(root, 15, 37);

    printTree(root);


    return 0;
}

程序应该打印出带有正确子代的树,但是在运行代码时,我收到了分段错误。

1 个答案:

答案 0 :(得分:1)

因此,显然,在创建新节点时,我没有在while循环中将child_list设置为NULL。感谢Retired Ninja提出解决方案!