douxiza9868 2019-05-20 01:39
浏览 211
已采纳

为什么`list.Remove()`试图显式避免内存泄漏? [重复]

This question already has an answer here:

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?

</div>
  • 写回答

1条回答 默认 最新

  • dsgawmla208057 2019-05-20 03:59
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料