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

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

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退