简体   繁体   中英

What happens to dynamically allocated memory in a doubly-linked list when it's deleted?

Suppose I have a doubly-linked list that has a pointer to the first node called "first." Now suppose that I want to create a function for this doubly-linked list that removes the "first" node (suppose the function accomplishes what's been done in the second picture; namely, a new pointer node has been declared as the previous first and first has been iterated once). Now my question is: if I delete the new first, does first's PREV now point to NULL? If not, what does it point to? Essentially, I want to know if I need to explicitly define first->PREV = NULL or whether deleting the new first will accomplish the same task.

Note: if it's not clear, up arrows are for PREV and down arrows are for NEXT.

在此处输入图片说明

You need to do it explicitly. When you deallocate an object, pointers that are pointing to it are not reset to null; they are left dangling.

When you call delete you just free that memory, if the pointer points to that area of memory it doesn't change it's value.
So in the function that deletes the node you also have to set the pointer to the deleted area to NULL (or nullptr).

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