I am trying to write a simple tree program in C, after a long long time :) but am stuck at the code where I add more nodes to my root node
Here is the code snippet:
struct node* root;
struct node* new_node;
// Add a node
new_node = malloc(sizeof(struct node*));
new_node -> left = NULL;
new_node -> data = 934;
new_node -> right = NULL;
// Mark this as root
root = new_node;
// Add a node
new_node = malloc(sizeof(struct node*));
new_node -> left = NULL;
new_node -> data = 967;
new_node -> right = NULL;
// Make this left node of root
root -> left = new_node;
// Add a node
new_node = malloc(sizeof(struct node*));
new_node -> left = NULL; // This line is the problem
new_node -> data = 612;
new_node -> right = NULL;
The line which is causing issue is marked with comment. The moment I make it NULL, the data 967 becomes 0.
However, if I put the new_node code in a function and call
root = new_node(934)
root -> left = new_node(967)
root -> right = new_node(612)
That works fine. I tried gdb on my code but could not understand why it would happen