Skip to content

go.slice_memory_leak

Performance Medium

Detects slice operations that retain references to underlying arrays, causing memory leaks.

Slice memory leaks cause:

  • Hidden memory retention — Small slice keeps large array alive
  • Gradual memory growth — Leaks accumulate over time
  • Hard to diagnose — Memory profiler shows slices, not retained arrays
// ❌ Before (retains entire array)
func getPrefix(data []byte) []byte {
return data[:10] // Keeps entire backing array!
}
// ✅ After (copies to new slice)
func getPrefix(data []byte) []byte {
prefix := make([]byte, 10)
copy(prefix, data[:10])
return prefix // Only 10 bytes retained
}
  • Returning slice of large input
  • Storing sub-slices in long-lived structures
  • Appending without copying when source is discarded

Unfault generates copy patterns:

result := make([]T, len(subslice))
copy(result, subslice)