1

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.

coder666
  • 41
  • 7
  • If you still have these 3 lines but in the second line change old to head - the code will be the same and no memory leak will be introduced. – Artemy Vysotsky Sep 07 '17 at 18:16

1 Answers1

4

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.

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • the code I was looking at did not create head with 'new' though is this an error? – coder666 Sep 07 '17 at 20:32
  • @coder666 You aren't really deleting `head`. You are deleting what `head` points at. `head` could point at any `Node`, and if `head` points at a `Node` created by `new`, someone must `delete` it sooner or later. Keyword: "Ownership semantics". In this case, the linked list is the owner of the `Node` and `head` is where the linked list stores the reference to the `Node`. As for `head` itself, it is an automatic variable that will be taken care of for you when it goes out of scope. – user4581301 Sep 07 '17 at 21:13
  • I get it ! Thank you ! – coder666 Sep 07 '17 at 21:16