0

I am trying to remove an element from a slice and I am wondering if this way will cause any memory leak in the application.

func RemoveElementInSlice(list []int32, idx int) []int32 {
    list[idx] = list[len(list)-1]
    list = list[:len(list)-1]
    return list
}

Here list is the slice from which I want to remove the element at index idx. If this might cause a memory leak what is the best & safe way to do it?

I_dont_know
  • 341
  • 1
  • 4
  • 17
  • See related: [Does go garbage collect parts of slices?](https://stackoverflow.com/questions/28432658/does-go-garbage-collect-parts-of-slices/28432812#28432812) – icza May 21 '21 at 08:04

1 Answers1

2

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.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • This is the type of memory leak reminiscent of item 7 in Josh Bloch's _Effective Java_ (3rd edition). – jub0bs May 21 '21 at 08:54