Kunal
Kunal

Reputation: 511

Pointer Initialization : When to assign NULL to the initialized pointer?

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 ??

Upvotes: 1

Views: 201

Answers (4)

jimmyfever
jimmyfever

Reputation: 387

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.

Upvotes: 1

neeKo
neeKo

Reputation: 4280

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

Upvotes: 1

fge
fge

Reputation: 121730

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().

Upvotes: 3

David Heffernan
David Heffernan

Reputation: 613003

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.

Upvotes: 2

Related Questions