I ran into this piece of code in a (fairly well respected) book. (Note: "head" is a pointer of type Element)
Stack::~Stack(){
while(head){
Element *next = head->next;
delete head;
head = next;
}
return;
}
From my understanding, the delete keyword de-allocates the memory assigned to a pointer. How is it that the author has used the pointer in the next line, immediately after de-allocating it? This confused me a bit. Am I missing something really obvious?
How is it that the author has used the pointer in the next line, immediately after de-allocating it?
The author is reassigning the pointer to the next element.
The delete
is deallocating the memory pointed to by head. It doesn't "deallocate" the pointer itself - the pointer will still exist and being usable.
head = next
then makes head
point to a different chunk of memory (the chunk pointed to by next
). The memory that was deleted is never used again, so there is no issue.