[英]Segmentation fault creating a binary search tree in C
我剛剛開始學習C語言中的樹,並且我的代碼不斷出現分段錯誤。 該代碼用於創建樹,然后返回樹中的最小和最大值。 我查看了其他人的代碼,但似乎找不到我所犯的錯誤。 如果有人可以發現它,將非常有幫助。
#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);
}
}
這行:
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.