Home >Backend Development >Golang >Does Deleting a Map Entry of Pointers Cause Memory Leaks in Go?
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.
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.
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 := &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.
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!