在BinaryTree中为子节点分配NULL时出现分段错误

时间:2013-11-24 04:23:32

标签: c segmentation-fault

#include<stdio.h>
#include<stdlib.h>

typedef struct BTreeNode BTNode;
struct BTreeNode
{
int value;
struct BTreeNode *left_child,*right_child;
};

int insert(int input_value, BTNode *head_node)
{
    BTNode *temp,*head;
    temp->value = input_value;
    temp->left_child = NULL;
    temp->right_child = NULL;
    head = head_node;
//  while(1)
    {
        if(head == NULL)
        {
            head = temp;
//          break;
            return 0;
        }
        if(temp->value > head->value)
        {
            head = head->right_child;
        }
        else if(temp->value < head->value)
        {
            head = head->left_child;
        }
        else
        {
//          break;
        }
            printf("Inserted successfully\n");
    }
    return 1;
}

int main()
{
    BTNode *root=NULL;
    insert(23,root);
}

我试图在二进制搜索树中插入一个新值。 在下面的代码中我得到了“temp-&gt; left_child = NULL;”的分段错误。插入函数中的行。我不明白我为什么会这样,任何人都可以帮我解决???

5 个答案:

答案 0 :(得分:0)

temp = malloc (sizeof (BTNode))

你从未分配过空间 对于temp指向的位置,所以它试图将数据保存到内存中 那不属于它。这会导致意外行为。您 很幸运,你有分段错误。

注意:您打算如何更改树的根?我不能 从你的代码中算出来。也许你可以返回根节点 每次从你的功能开始:BTNode* insert(int input_value, BTNode *head_node) 或使用双指针,如:int insert(int input_value, BTNode **head_node)和 在*head_nodeinsert。看看here以获得关于指针的好读物 和C中的内存分配。

答案 1 :(得分:0)

当然,缺少内存分配。你向你的函数传递一个NULL root参数,然后你声明一个没有任何内存分配的指针temp,然后你取消引用它 - 没有好处。

答案 2 :(得分:0)

BTNode *temp,*head;
temp->value = input_value;

正在使用Temp而不分配空间。所以它应该是:

BTNode *temp,*head;
temp = malloc(sizeof(BTreeNode));
temp->value = input_value;

答案 3 :(得分:0)

没有为temp分配内存。你应该这样做:

BTNode * createNode()
{
return ((node *)malloc(sizeof(node)));
} 

int insert(int input_value, BTNode *head_node)
{
    BTNode *temp,*head;
    temp = createNode();
    temp->value = input_value;
    temp->left_child = NULL;
    temp->right_child = NULL;
}

答案 4 :(得分:0)

首先将内存分配给临时节点。它应该是这样的,

BTNode *temp,*head;
    temp = malloc(sizeof(BTNode));
    temp->value = input_value;
    temp->left_child = NULL;
    temp->right_child = NULL;
相关问题