简体   繁体   中英

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.

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 new ed must be delete d or you have a leak.

Say you have

在此处输入图片说明

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

在此处输入图片说明

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,

在此处输入图片说明

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 ,

在此处输入图片说明

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

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM