Home >Backend Development >Golang >Can Deleting a Map Entry Lead to Memory Leaks in Go?
A common concern when manipulating data structures in Go is the potential for memory leaks. This question focuses on whether deleting an entry from a map of pointers can lead to such a leak.
While the documentation doesn't explicitly address this, inspecting the Go runtime source code reveals that when an entry is deleted from a map, both the key and value storage are cleared (zeroed). This means any pointers contained within are also cleared.
// Clear key storage. memclr(k, uintptr(t.keysize)) // Clear value storage. v := unsafe.Pointer(uintptr(unsafe.Pointer(b)) + dataOffset + bucketCnt*uintptr(t.keysize) + i*uintptr(t.valuesize)) memclr(v, uintptr(t.valuesize))
To corroborate this, we can create a sample program with a map of pointers and register a finalizer to catch when the pointer becomes unreachable:
import ( "fmt" "runtime" "sync" "time" ) type point struct { X, Y int } func main() { // Create a map and put a pointer value in it, with a finalizer. m := map[int]*point{} 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) // Delete the entry from the map. delete(m, 1) // Force garbage collection. runtime.GC() // Sleep to ensure the finalizer has a chance to run. time.Sleep(time.Second) // Print the map to verify the map itself wasn't garbage collected. fmt.Println(m) }
Running this will produce the following output:
Put in map: 0x1040a128 &{X:1 Y:2} Finalized: 0x1040a128 &{X:1 Y:2} map[]
As you can see, the finalizer is called when the pointer is removed from the map and becomes unreachable, demonstrating that there is no memory leak.
The above is the detailed content of Can Deleting a Map Entry Lead to Memory Leaks in Go?. For more information, please follow other related articles on the PHP Chinese website!