The following is an excerpt from the code to a singly linked list implementation from Data Structures and Algorithms in C++ (2nd Edition) by Adam Drozdek that involves deleting a node with a given value.
IntNode *tmp = head->next;
head = head->next;
delete tmp;
(head is defined elsewhere as an IntNode*) Are there typos in this code fragment, or is my mental processor incorrect in that head will always be a null pointer after every execution of the above code fragment?
When you write
delete tmp, you are deleting the object pointed to bytmp. However, after deletingheadwill still point to the same place. Dereferencing it (*head) will cause problems, because the objectheadis pointing to has been deleted.