[英]Binary tree in C - Segmentation fault
#include <stdio.h>
#include <stdlib.h>
typedef struct nod{
int data;
struct nod *left,*right;
}NOD;
NOD * generate(NOD * root)
{
NOD *r,*p;
int d=-1,value,line,position,i,f,v;
if(root==NULL)
{
do{
printf("Would you like to create the root node?\n\n1 - yes\n0 - no\n");
scanf("%d",&d);
switch(d)
{
case 1:
printf("Value=");
scanf("%d",&value);
root=add_root(value);
break;
case 0:
return NULL;
break;
default:
printf("Command unrecognized!\n");
break;
}
} while(d==-1);
if(root!=NULL)
printf("Root node successfully created!\n");
else
printf("Error: could not create root node!\n");
d=-1;
do{
printf("Continue adding nodes?\n\n1 - yes\n0 - no\n");
scanf("%d",&d);
switch(d)
{
case 1:
printf("Insert the line and the position of the node you wish to add (root node has line=0, position=0)\nLine=");
scanf("%d",&line);
printf("Position ( less or equal with 2^$line-1 )=");
scanf("%d",&position);
printf("Value=");
scanf("%d",&value);
r=p=root;
for(i=line-1;i=0;i--)
{
f=power(2,i);
if(position & f == f) // if the i-(st,nd,rd,th) bit of "position" is 1, then (position & f == f) is true and *r will go right
{
p=r;
r=r->right;
v=1;
}
else
{
p=r;
r=r->left;
v=0;
}
}
if(v==0)
p=add_left(&r,value);
if(v==1)
p=add_right(&r,value);
break;
case 0:
return root;
break;
default:
printf("Command unrecognized!\n");
break;
}
} while(d==-1);
}
else
{
...
}
NOD * add_left(NOD **p,int value)
{
NOD * r;
r=malloc(sizeof(NOD));
r->data=value;
r->left=NULL;
r->right=NULL;
(*p)->left=r;
return r;
}
NOD * add_right(NOD **p,int value)
{
NOD * r;
r=malloc(sizeof(NOD));
r->data=value;
r->left=NULL;
r->right=NULL;
(*p)->right=r;
return r;
}
NOD * add_root(int value)
{
NOD * x;
x=malloc(sizeof(NOD));
x->data=value;
x->left=NULL;
x->right=NULL;
return x;
}
}
int main() {
NOD *root=NULL;
root=generate(root);
return 0;
}
我尝试过创建一个创建二叉树的程序,但是我不断收到SIGSEGV Segmentation错误,但我不明白为什么。 你能告诉我我做错了什么吗?
if(position & f == f) // if the i-(st,nd,rd,th) bit of "*position*" is 1,
// then (position & f == f) is true and *r will go right
您如何看待这部分?
line是树的级别(根有line = 0)
position是节点从左到右的位置(根的位置为= 0)
您已经加粗了一个有问题的部分:
if(position & f == f)
==
优先级比&
优先级高,因此被解析为
if(position & (f == f))
并且与if (position & 1)
,而不是您想要的。
此外,您有错误的循环条件
for(i=line-1;i=0;i--)
测试可能应该是i >= 0
,否则循环永远不会执行( i = 0
是赋值为0的赋值)。
如果这些是固定的,并且执行了循环,则在第一个迭代r
为空指针之后,则下一个循环迭代将导致崩溃,原因是r = r->right;
,或者,如果循环仅迭代一次,则add_left(&r,value);
(或add_right
)在倒数第二行上取消引用空指针,以尝试访问其left
指针(分别为right
):
NOD * add_left(NOD **p,int value)
{
NOD * r;
r=malloc(sizeof(NOD));
r->data=value;
r->left=NULL;
r->right=NULL;
(*p)->left=r; // *p == NULL here
return r;
}
在这条线
for(i=line-1;i=0;i--)
我想你是说
for(i=line-1;i!=0;i--)
否则,循环将不会执行( i=0
为false
)。 这导致v
具有未定义的值(因为它从未被初始化)。 尽管这很可能不会导致段错误,但是当您覆盖根的左/右子树时,它将导致内存泄漏。
另外,默认的switch
分支不会更改d
的扫描值,这意味着您将继续使用NULL
根(检查root != NULL
的错误分支root != NULL
不会退出该函数)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.