Home >Backend Development >Golang >Does Deleting a Map Entry of Pointers Cause Memory Leaks in Go?

Does Deleting a Map Entry of Pointers Cause Memory Leaks in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 03:54:30547browse

Does Deleting a Map Entry of Pointers Cause Memory Leaks in Go?

In Go, Does Deleting an Entry in a Map of Pointers Cause Memory Leak?

While slicing or deleting elements in a slice of pointers may pose a potential memory leak, let's explore whether this holds true for a map as well.


Inspecting the Sources

Checking the Go runtime sources reveals that in the mapdelete() function, both the key and value storage are cleared upon deletion.

<br>558 func mapdelete(t <em>maptype, h </em>hmap, key unsafe.Pointer) {</p>
<pre class="brush:php;toolbar:false">    // ...

600 memclr(k, uintptr(t.keysize))
601 v := unsafe.Pointer(uintptr(unsafe.Pointer(b)) dataOffset bucketCntuintptr(t.keysize) iuintptr(t.valuesize))
602 memclr(v, uintptr(t.valuesize))

    // ...

618 }

This means any pointers in keys or values are zeroed, breaking their references to the map's internal data structures.

Constructing a Test to Verify

To further demonstrate this, we can construct a test:

<br>type point struct {</p>
<pre class="brush:php;toolbar:false">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 := &amp;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)

}

Upon running this test, we observe that the registered finalizer is called, confirming the pointer's removal from the map and subsequent garbage collection.

Conclusion

In Go, deleting an entry from a map of pointers does not cause a memory leak. Both the key and value storage are cleared upon deletion, releasing any pointers they held, ensuring proper garbage collection.

The above is the detailed content of Does Deleting a Map Entry of Pointers Cause Memory Leaks in Go?. 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