As explained in "Kind-of Memory Leaking Caused by Subslices":
Similarly to substrings, subslices may also cause kind-of memory leaking.
In the following code, after the g function is called, most memory occupied by the memory block hosting the elements of s1 will be lost (if no more values reference the memory block).
var s0 []int
func g(s1 []int) {
// Assume the length of s1 is much larger than 30.
s0 = s1[len(s1)-30:]
}
If we want to avoid the kind-of memory leaking, we must duplicate the 30 elements for s0, so that the aliveness of s0 will not prevent the memory block hosting the elements of s1 from being collected.
func g(s1 []int) {
s0 = make([]int, 30)
copy(s0, s1[len(s1)-30:])
// Now, the memory block hosting the elements
// of s1 can be collected if no other values
// are referencing the memory block.
}
---
But you can investigate that with pprof, as illustrated in "[Golang slice memory leak collection][2]"
```go
//Add pprof package in import
_ "net/http/pprof"
Then:
go tool pprof http://127.0.0.1:9999/debug/pprof/heap
See also icza's answer.