Setting pointers to nil to prevent memory leak in Golang

前端 未结 2 1507
南笙
南笙 2020-12-08 22:13

I\'m learning Go, and as an exercise I wanted to implement a linked list. For reference I looked at the official Go code (https://golang.org/src/container/list/list.go) . On

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 22:22

    Golang garbage collector is based on the tri-color mark-and-sweep algorithm. In short, every memory you're program use is associated to a color. The color determine if the memory shall be garbaged or not.

    This algorithm will flag a memory to be freed if this memory is not referenced somewhere (directly and indirectly). But if we take a look at the code:

    e.prev.next = e.next
    e.next.prev = e.prev
    

    This copy the pointer in e.next into e.prev.next. Now, let's say you want to update e.prev.next by a new fully created element.

    The previously removed element won't be garbaged because it is still referenced by e.next.

    This is why those lines exist:

    e.next = nil // avoid memory leaks
    e.prev = nil // avoid memory leaks
    

    This prevent from leaving old references, and thus prevent from memory leaks.

提交回复
热议问题