[英]Segmentation fault creating a binary search tree in C
I just started learning about trees in C and I keep getting a segmentation fault with my code. 我刚刚开始学习C语言中的树,并且我的代码不断出现分段错误。 The code is meant to create the tree then return the smallest and biggest values in the tree.
该代码用于创建树,然后返回树中的最小和最大值。 I have looked at other peoples code and I can't seem to find the mistake that I am making.
我查看了其他人的代码,但似乎找不到我所犯的错误。 If anyone can spot it that will be very helpful.
如果有人可以发现它,将非常有帮助。
#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);
}
}
This line : 这行:
node* newNode = (node*)malloc(sizeof(node*));
You are allocating sizeof(node *)
bytes which is actually the size of a pointer for you system. 您正在分配
sizeof(node *)
字节,这实际上是系统指针的大小。 What you want is to allocate enough memory to hold the structure itself and not a pointer to it. 您想要分配足够的内存来容纳结构本身,而不是指向它的指针。 Something like this will work :
这样的事情将工作:
node* newNode = (node*)malloc(sizeof(node) * sizeof(char));
change this line: 更改此行:
node* newNode = (node*)malloc(sizeof(node*));
to this: 对此:
node* newNode = (node*)malloc(sizeof(node));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.