Home  >  Article  >  Backend Development  >  Do Maps of Pointers in Go Need Special Handling for Memory Leaks?

Do Maps of Pointers in Go Need Special Handling for Memory Leaks?

Susan Sarandon
Susan SarandonOriginal
2024-10-23 22:25:30987browse

Do Maps of Pointers in Go Need Special Handling for Memory Leaks?

Memory Leak in Go: Map of Pointers

Problem:

Despite the documentation advising caution when manipulating slices of pointers, it's unclear whether similar precautions are necessary for maps of pointers. Specifically, should entries be set to nil before deletion or the entire map be cleared? Will the garbage collector adequately handle memory deallocation?

Investigation:

Examining the Go runtime source code (runtime/hashmap.go) reveals that both key and value storage are cleared during map deletion, zeroing any pointers contained within them.

Proof through Example:

The following code demonstrates the absence of a memory leak:

<code class="go">type point struct {
    X, Y int
}

var m = map[int]*point{}

func main() {
    fillMap()
    delete(m, 1)
    runtime.GC()
    time.Sleep(time.Second)
    fmt.Println(m)
}

func fillMap() {
    p := &point{1, 2}
    runtime.SetFinalizer(p, func(p *point) {
        fmt.Printf("Finalized: %p %+v\n", p, p)
    })
    m[1] = p
    fmt.Printf("Put in map: %p %+v\n", p, p)
}</code>

Output:

Put in map: 0x1040a128 &{X:1 Y:2}
Finalized: 0x1040a128 &{X:1 Y:2}
map[]

This example uses a pointer to a struct, registers a finalizer to detect when the pointer becomes unreachable, and then deletes its corresponding map entry. Despite no other references to the pointer, its finalizer is called upon garbage collection, indicating its removal from the map.

Conclusion:

Based on the source code inspection and example test, clearing entries or the entire map before deletion is not necessary in Go. The garbage collector will properly handle memory deallocation even when maps contain pointers.

The above is the detailed content of Do Maps of Pointers in Go Need Special Handling for Memory Leaks?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn