【问题标题】:segmentation fault when assigning NULL to child Node in BinaryTree将 NULL 分配给 BinaryTree 中的子节点时出现分段错误
【发布时间】:2013-11-24 04:23:32
【问题描述】:
#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->left_child = NULL;”处遇到分段错误插入函数中的行。我不明白为什么我会得到那个任何人都可以帮我吗???

【问题讨论】:

    标签: c segmentation-fault


    【解决方案1】:

    temp = malloc (sizeof (BTNode))

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

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

    【讨论】:

    • 当我们处理指针时,我们不能永远使用 main 中的根作为根,因为我们插入值时考虑到根作为二叉树的根???
    • 我的意思是对指针所做的更改将具有全局范围。所以我们需要再次返回 root 吗??
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      BTNode *temp,*head;
      temp->value = input_value;
      

      正在使用临时但未分配空间。所以应该是:

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

      【讨论】:

        【解决方案4】:

        没有分配给 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;
        }
        

        【讨论】:

          【解决方案5】:

          先给临时Node分配内存。应该是这样的,

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-11-08
            • 1970-01-01
            • 2013-11-08
            • 1970-01-01
            相关资源
            最近更新 更多