Reputation: 40
Before calling the free(); function if I don't assign NULL value to the link part of the node that I want to delete, what will be the problem ? I reviewed some codes of deleting nodes in other websites, but I found no assignment of NULL value to the link part. They just called the free(); function. Please reply to remove my confusion. Thank you.
struct node
{
int data;
struct node * next;
}
struct node * head = NULL; //This is the head node.
/* Here some other functions to create the list */
/* And head node is not going to be NULL here, after creating the list */
void deleteFirstNode()
{
struct node * temp = head;
head = temp->next;
temp->next = NULL; //my question is in this line, is this line necessary?
free(temp);
}
Upvotes: 0
Views: 149
Reputation: 310950
This function can invoke undefined behavior when will be called for an empty list due to these statements
struct node * temp = head;
head = temp->next;
because in this case head
is equal to NULL
.
The function frees the memory occupied by an object of the type struct node
. So there is no sense to change the deleted object. This statement
temp->next = NULL; //my question is in this line, is this line necessary?
is redundant.
It is the same as before deleting the node to write
temp->data = INT_MAX;
This does not influence on the list.
The function can look like
void deleteFirstNode()
{
if ( head != NULL )
{
struct node *temp = head;
head = head->next;
free( temp );
}
}
Also it is a bad idea to define function that depend on global variables. In this case you will be unable for example to create more than one list in the program. It is better when the pointer to the head node is passed to the function deleteFirstNode by reference.
In this case the function can look like
void deleteFirstNode( struct node **head )
{
if ( head != NULL )
{
struct node *temp = *head;
*head = ( *head )->next;
free( temp );
}
}
And the function can be called like
deleteFirstNode( &head );
Upvotes: 1
Reputation: 24726
No, the line
temp->next = NULL;
is not necessary. Any data in the node pointed to by temp
will become invalid as soon as free
is called, so changing any values inside that node immediately before they become invalid will have no effect.
Upvotes: 1