mirror of
https://github.com/golang/go.git
synced 2025-05-05 15:43:04 +00:00
Adds clarity on how deleting elements from a slice can cause a memory leak thanks to the underlying array
parent
7eb5143fe4
commit
786ba4b382
@ -44,7 +44,7 @@ a[i] = a[len(a)-1]
|
||||
a = a[:len(a)-1]
|
||||
|
||||
```
|
||||
**NOTE** If the type of the element is a _pointer_ or a struct with pointer fields, which need to be garbage collected, the above implementations of ` Cut ` and ` Delete ` have a potential _memory leak_ problem: some elements with values are still referenced by slice ` a ` and thus can not be collected. The following code can fix this problem:
|
||||
**NOTE** If the type of the element is a _pointer_ or a struct with pointer fields, which need to be garbage collected, the above implementations of ` Cut ` and ` Delete ` have a potential _memory leak_ problem: some elements with values are still referenced by slice ` a `'s underlying array, just not "visible" in the slice. Because the "deleted" value is referenced in the underlying array, the deleted value is still "reachable" during GC, even though the value cannot be referenced by your code. If the underlying array is long-lived, this represents a leak. The following code can fix this problem:
|
||||
> **Cut**
|
||||
```go
|
||||
copy(a[i:], a[j:])
|
||||
|
Loading…
x
Reference in New Issue
Block a user