[英]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.