【发布时间】:2020-01-31 13:56:01
【问题描述】:
节点插入代码引发分段错误。 当我尝试打印存储在根节点中的数据时,此代码会引发分段错误。
下面是二叉搜索树插入程序的实现。 这个程序使用递归来插入一个给定的节点。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *make (int);
struct node *insert (struct node *, int);
void
main ()
{
struct node *root;
root = NULL;
insert (root, 2);
insert (root, 3);
insert (root, 4);
insert (root, 5);
insert (root, 6);
insert (root, 7);
printf ("%d", root->data);
}
struct node *
make (int x)
{
struct node *temp;
temp = (struct node *) malloc (sizeof (struct node *));
temp->data = x;
temp->left = NULL;
temp->right = NULL;
return temp;
}
struct node *
insert (struct node *root, int x)
{
if (root == NULL)
{
root = make (x);
}
else
{
if (x <= root->data)
{
root->left = insert (root->left, x);
}
else if (x > root->data)
{
root->right = insert (root->right, x);
}
}
return root;
}
【问题讨论】:
-
你的堆栈跟踪显示了什么?
-
那么你很幸运!分段错误会将您的调试器带到发生错误的确切行和指令,并向您显示该点的每个变量和内存位置的值。
-
root == NULL- root 是本地指针,它不会修改外部的 root。因此root->data在printf里面是NULL->data。 -
试想一下,你在
insert中使用make为root分配内存:main怎么会看到这个? -
谢谢 - 卡米尔库克。我应该声明 root = insert(root,2)。
标签: c malloc binary-search-tree dynamic-memory-allocation