Memory leaks
In the subsections that follow, we are going to talk about memory leaks in slices and maps. A memory leak happens when a memory space is allocated without being completely freed afterward.
We are going to begin with memory leaks caused by wrongly used slices.
Slices and memory leaks
In this subsection, we are going to showcase code that uses slices and produces memory leaks and then illustrate a way to avoid such memory leaks. One common scenario for memory leaks with slices involves holding a reference to a larger underlying array even after the slice is no longer needed. This prevents the GC from reclaiming the memory associated with the array.
The code in slicesLeaks.go
is the following:
package main
import (
"fmt"
"time"
)
func createSlice() []int {
return make([]int, 1000000)
}
func getValue(s []int) []int {
val := s[:3]
return val
}
func main() {
for i := 0; i < 15; i++ {
message := createSlice...