i am trying to create a tree using struct in C
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node * next, * left, * right;
};
struct node * createtree(int data){
struct node * kosong = (struct node*)malloc(sizeof(struct node*));
kosong->data = data;
kosong->left = kosong->right = NULL;
return kosong;
}
void printtree(struct node * tree){
if(tree == NULL) return;
printtree(tree->left);
printf("%d ",tree->data);
printtree(tree->right);
}
int main(){
struct node * pohon = NULL;
pohon = createtree(1);
pohon->left = createtree(2);
pohon->right = createtree(3);
pohon->left->left = createtree(4);
pohon->left->right = createtree(5);
printtree(pohon);
}
whenever i compile it gets segmentation fault. Then i try to delete the * next pointer and it compiles & run successfully. I know tree does not need the * next pointer , but i dont see why it wont compile just because of another same pointer. Appreciate your help.
To help you understanding the mistake:
first line in function createtree(int data):
struct node * kosong = (struct node*)malloc(sizeof(struct node*));
should actually be
struct node * kosong = (struct node*)malloc(sizeof(struct node));
Because you are allocating memory for a struct node, not for a pointer to a struct node.
And this is the actual reason for your segfault. I compiled the code with only fixing this mistake and it worked absolutely fine. Of course you should try initializing all pointers and variables, as doing not might end in undefined behaviour, which can be anything, just like segmentation faults.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments