1
typedef struct nodetype 
{
 int data;
 struct nodetype * left;
 struct nodetype * right;
}node;

typedef node * tree;

tree newNode(int data)
{
 tree temp;
 temp = NULL;
 temp = (tree)malloc(sizeof(nodetype));
 temp->data = data;
 temp->right = NULL;
 temp->left = NULL;
 return temp;
}

Here in the function newNode, to create a node we assign NULL value to the "temp". I dont understand whether this is necessary. What will be the implications if we dont initialize it with NULL and in which cases should I take care of assigning a ptr to NULL while initializing it ??

1
  • That isn't initialization. Initialization is when you specify a value in the same statement that declares the value, e.g. tree temp = NULL;. Commented Dec 17, 2011 at 22:35

4 Answers 4

3

It is totally unnecessary since it is immediately overwritten by malloc() which will set it to... NULL on allocation failure, which means the code is buggy!

There should be a:

if (!temp)
    return temp;

right after the malloc().

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

Comments

2

temp = NULL in the code above is not necessary since that value is immediately overwritten. Your compiler would probably eliminate the redundant code at the optimization stage. Simply remove that line of code.

Comments

1

You initialize nodes to NULL so you could differentiate empty nodes from the ones that aren't (by checking for NULL). Otherwise you'd have no way of telling whether or not a node is empty. This is talking about the left and right nodes. There is no apparent reason why temp is initiated to NULL, you can remove that.

You assign a pointer to NULL when you don't know if you will use it to point to something, and you will have code that checks if it has been assigned to NULL or not so it can perform some logic (like moving through a tree).

Comments

1

I suspect that the NULL assignment is because the programmer had a strict policy of always assigning his or her variables. Not a bad policy, though it's not necessary here.

Comments

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.