If the variable temp
could possibly be used again later on in the code, then it is good practice to set it to NULL.
There are two reasons you'd normally set a pointer to NULL after releasing it.
1.) Once you release a pointer the memory at the address pointed to is no longer available to your program. Theoretically, that memory could now be used by any other program, including the operating system itself! Attempting to release a pointer that has already been released and thus points to who knows what could cause a huge problem. Luckily modern operating systems protect against this but the program will still crash with an illegal access error. Releasing a null pointer OTOH will do absolutely nothing.
2.) You should always check that a pointer isn't NULL before de-referencing it with the *
operator. De-referencing a NULL pointer will cause a run-time error. De-referencing a released pointer that points to some arbitrary memory is even worse. A released pointer should always be set to NULL
so the later code can assume a non-null pointer points to valid data. Otherwise there is no way of knowing whether the pointer is still valid.
As for the original question, the pointer variable temp
is declared as a local variable in a short function where it is never used again. In this case it's unnecessary to set it to NULL since it goes out of scope as soon as the function returns.
However, the line...
(*head)->next = (*head)->next->next;
fails to makes sure (*head)->next
is not null before attempting to de-reference, a no-no.
A better version would be...
int DeleteAfter(Node **head){
Node *node_after = NULL;
if(*head==NULL)
return -1;
node_after = (*head)->next;
if(node_after == NULL)
return -1;
(*head)->next = node_after->next;
delete node_after;
return 0;
}
Now the person using the function can check whether the node deletion was successful by the return value and there is no risk of trying to delete a non-existent node.