coder666
coder666

Reputation: 41

Pointers in a linked list example

I was implementing a linked list until I came across

void StringLinkedList::removeFront(){ 

StringNode *old = head;
head = old -> next;
delete old;

}

I was wondering why not just do head = head->next (instead of head = old->next), how does this create a memory leak when there is nothing pointing to the previous address (since head the head node is now pointing to the next node).

Thank you so much.

Upvotes: 1

Views: 77

Answers (1)

user4581301
user4581301

Reputation: 33982

C++ does not have automated garbage collection like some other languages that release storage once it is no longer referenced. There are a number of reasons for this, and a discussion on the topic can be found in Why doesn't C++ have a garbage collector?.

This means that which is newed must be deleted or you have a leak.

Say you have

enter image description here

If you do not delete the original value of head before overwriting head,

enter image description here

the address of Node 1 is no longer known, making it next to impossible to track down the allocation in order to delete it. This forces a leak.

But if you delete head before re-pointing it,

enter image description here

you can't head->next to find the next node, and you lose and leak the whole list.

However, if you make a temporary copy of the address of head,

enter image description here

old in this case, you can safely re-point head

enter image description here

and still have the address of the allocation you need to delete stored in old.

Upvotes: 4

Related Questions