I just started learning about trees in C and I keep getting a segmentation fault with my code. 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. 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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.