为什么我出现细分错误(核心已转储)

时间:2019-11-12 11:06:56

标签: c tree segmentation-fault

我刚开始学习树并想实现它。此代码可以编译,但是运行后出现分段错误。我有

有2个功能

1。“ new”这将创建一个新节点以添加到树中

2。“插入”这会将数据插入树,这是一个递归函数

我只想检查数据是否已存储,所以我尝试在根节点中打印该值,但随后出现分段错误

我检查了所有看似正确的内容,但不知道出了什么问题

struct node
{
    int data;
    struct node* left;
    struct node* right;
};
struct node* new(int data)
{
    struct node* newnode = (struct node*)malloc(sizeof(struct node*));
    newnode->data=data;
    newnode->left=newnode->right=NULL;
    return newnode;
}
struct node* insert(struct node* root,int data)
{
    if(root==NULL)
    {
        new(data);
    }
    else if (data<=root->data)
    {
        root->left =insert(root->left,data);
    }
    else
    {
        root->right=insert(root->right,data);
    }
    return root;
}


void main()
{
    struct node* root = NULL;
    root = insert(root,15);
    root = insert(root,20);

    printf("%d",root->data);
}

我希望输出为15,但会出现分段错误。

3 个答案:

答案 0 :(得分:1)

您必须更改malloc表达式。您应该malloc struct节点而不是struct node *。另外,您应该将void main更改为int main

答案 1 :(得分:0)

首先,您确定要将struct node* newnode = (struct node*)malloc(sizeof(struct node*));更改为struct node* newnode = (struct node*)malloc(sizeof(struct node));,删除sizeof中的星号,否则无论结构的大小,您都将获得8个字节的大小;)

然后您会得到一个stackoverflow错误,但是我让您搜索那个; p

答案 2 :(得分:0)

您不在任何地方存储数据。在new(data);函数中将root = new(data);更改为insert

另一个错误是struct node* newnode = (struct node*)malloc(sizeof(struct node*))应该是struct node* newnode = malloc(sizeof(*newnode))。这样既可以修复错误,又可以改善其他原因。

此外,void main()应该是int main()