分段错误在C语言中创建二叉搜索树
我刚开始学习C语言中的树,我的代码经常出现分段错误。代码旨在创建树,然后返回树中的最小值和最大值。我看了别人的代码,似乎找不到我犯的错误。如果有人能发现它,那将非常有帮助分段错误在C语言中创建二叉搜索树,c,tree,binary-search-tree,C,Tree,Binary Search Tree,我刚开始学习C语言中的树,我的代码经常出现分段错误。代码旨在创建树,然后返回树中的最小值和最大值。我看了别人的代码,似乎找不到我犯的错误。如果有人能发现它,那将非常有帮助 #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node{ int data; struct node* right; struct node* left; }nod
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
int data;
struct node* right;
struct node* left;
}node;
node* Insert(node* root, int data);
int Min(node* root);
int Max(node* root);
node* GetNewNode(int data);
int main(void){
int min, max, data, x;
node* root = NULL;
printf("how many elements would you like to be in the tree\n");
scanf("%i", &x);
for(int i = 0; i < x; i++){
scanf("%i", &data);
root = Insert(root, data);
}
min = Min(root);
max = Max(root);
printf("the min value is %i, and the max value is %i\n", min, max);
}
node* Insert(node* root, int data){
if(root == NULL){
root = GetNewNode(data);
}
else if(data <= root->data){
root->left = Insert(root->left, data);
}
else{
root->right= Insert(root->right, data);
}
return root;
}
node* GetNewNode(int data){
node* newNode = (node*)malloc(sizeof(node*));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
int Min(node* root){
node* temp = root;
if(root->left == NULL){
return root->data;
}
else{
return Min(root->left);
}
}
int Max(node* root){
node* temp = root;
if(root->right == NULL){
return root->data;
}
else{
return Max(root->right);
}
}
#包括
#包括
#包括
类型定义结构节点{
int数据;
结构节点*右;
结构节点*左;
}节点;
节点*插入(节点*根,int数据);
int Min(节点*根);
int Max(节点*根);
节点*GetNewNode(int数据);
内部主(空){
int最小值,最大值,数据,x;
node*root=NULL;
printf(“您希望在树中包含多少元素\n”);
scanf(“%i”和“&x”);
对于(int i=0;i左=插入(根->左,数据);
}
否则{
根->右=插入(根->右,数据);
}
返回根;
}
节点*GetNewNode(int数据){
node*newNode=(node*)malloc(sizeof(node*));
新建节点->数据=数据;
newNode->left=newNode->right=NULL;
返回newNode;
}
最小整数(节点*根){
节点*temp=root;
如果(根->左==NULL){
返回根->数据;
}
否则{
返回最小值(根->左);
}
}
int Max(节点*根){
节点*temp=root;
如果(根->右==NULL){
返回根->数据;
}
否则{
返回最大值(根->右);
}
}
此行:
node* newNode = (node*)malloc(sizeof(node*));
您正在分配sizeof(node*)
字节,它实际上是系统指针的大小。您想要的是分配足够的内存来保存结构本身,而不是指向它的指针。类似这样的方法会奏效:
node* newNode = (node*)malloc(sizeof(node) * sizeof(char));
更改此行:
node* newNode = (node*)malloc(sizeof(node*));
为此:
node* newNode = (node*)malloc(sizeof(node));
node*newNode=(node*)malloc(sizeof(node*))代码>-->node*newNode=(node*)malloc(sizeof(node))代码>或节点*newNode=malloc(sizeof(*newNode))代码>这是一个很好的捕获@BLUEPIXY。Mohammed如果您在GDB下执行并检查backtrace,将是一个很好的学习调试的机会。