Slice leaks
A slice leak is a small live header that keeps a large backing array reachable. len looks tiny; cap and the array are huge. The GC cannot free the unused tail.
Detailed Explanation
You read a 20 MiB file into data. You parse one header line and store line := data[:80]. line has length 80 and capacity millions. As long as line is reachable — in a cache, a struct field, a global — the 20 MiB array stays. That is the leak. It is not a use-after-free; it is forgotten capacity.
The fix is copy. out := make([]byte, len(line)); copy(out, line) or slices.Clone(line) or append([]byte(nil), line...). The new array is 80 bytes. data can be collected when nothing else points at it.
Substrings. s[i:j] on a string shares the bytes. Storing a small substring of a huge ReadFile string leaks the file. strings.Clone (Go 1.20+) or string(append([]byte(nil), s[i:j]...)) copies.
slices.Delete and leftover pointers. Before Go 1.22, append(s[:i], s[j:]...) left pointers in the unused cap that kept objects alive. Current slices.Delete zeros the tail. When you compact a []*T yourself, nil out the tail or use slices.Delete.
Caches. An LRU that stores []byte windows from a shared buffer will pin the buffer. Clone on insert.
What it costs. The process RSS grows while len of your cached slices stays small. pprof heap will show the backing arrays attributed to make or ReadFile, not to the tiny header you stored. Look at the retained size, not the slice length.
Code Examples
package main
import "slices"
func leak(data []byte) []byte {
return data[:80] // pins all of data
}
func noLeak(data []byte) []byte {
return slices.Clone(data[:80])
}
func main() {
data := make([]byte, 1<<20)
_ = noLeak(data)
}func cloneString(s string) string {
return string([]byte(s)) // copy; or strings.Clone(s)
}Common Gotchas
`slices.Clip(s)` sets `cap` to `len` but does not shrink the array
the tail is unreachable from this header, yet if another header exists the array stays. Clip does not copy.
`string(largeFile)[0:10]` still holds `largeFile`
`string(largeFile)[0:10]` still holds `largeFile`
`slices.Clone` is the usual fix for a stored window
`slices.Clone` is the usual fix for a stored window