Reputation: 1003
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
Upvotes: 2
Views: 1721
Reputation: 110108
new_node = malloc(sizeof(struct node*));
should be:
new_node = malloc(sizeof(struct node));
everywhere. Another possiblity is new_node = malloc(sizeof(*new_node));
.
You need to allocate an entire node to point to, not just a pointer to a node.
Since you didn't allocate enough memory for a node, you got undefined behavior when writing to the fields of the node, which in your case caused it to overwrite existing data.
Upvotes: 1