-1

The source code of container/list.Remove() tries to avoid memory leaks explicitly by assigning nil to specific variables, why should we do this? thanks!

The code is in the golang source code of version 1.12.

// remove removes e from its list, decrements l.len, and returns e.
func (l *List) remove(e *Element) *Element {
    e.prev.next = e.next
    e.next.prev = e.prev
    e.next = nil // avoid memory leaks
    e.prev = nil // avoid memory leaks
    e.list = nil
    l.len--
    return e
}

Can't GC handle this situation?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
jitianyu
  • 3
  • 1

1 Answers1

2

An element removed from a list cannot be pointing to other elements in the list after its removal.

Consider the list A -> B -> C -> D . And you remove the element B from the above list. Without the statement

e.next = nil

in the code snipped above, the memory layout will look like this.


A -> C > D
     ^
     |
     B

Now if the element B is still in use(say element B is used till the end of the progarm), It has a pointer to C. This means that C cannot be garbage collected even if C is removed from list later and is not required for anymore.

A similar case can occur for e.prev

Malice
  • 1,457
  • 16
  • 32