2

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

2
  • 1
    Well, it looks like an overwrite issue, yes? So, it's probably pointers and their targets, mallocs etc yes? So, as a debug check, printf out 'sizeof(struct node*)' to see how much memory you are allocating. Commented Jul 22, 2017 at 10:34
  • @MartinJames Yes, that is what I did after I received the answer below. Also I forgot that I was working on a 64 bit machine while using gdb, so calculated the size of my struct as 4 byte fields, mentally :) Commented Jul 22, 2017 at 10:41

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah !! Silly me. Thanks for pointing that out. So instead of assigning 24 bytes to my new_node it was just 8 bytes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.