理解内存泄漏在GO Slice
s:= []它: 长度变为1,但衬里数组仍未触及。第二个元素中未使用的指针仍是数组的一部分。 Since it's not being referred to by any slice, it becomes inaccessible and cannot be freed by the garbage collector, resulting in a memory leak.
Why Not Non-Pointers?With a slice of non-pointers ([]int):
t := []int{1, 2}
pointers and structss := []*int{new(int), new(int)}书籍{book1,book2} bkslice = bkslice [:1]
,即使Slice仅保留Book1,Book2的作者和标题字符串仍在存储器中作为数组的一部分。为了防止这种情况,请在切片之前为book2分配零值:
bkslice [1] = book {} bkSlice = bkSlice[:1]This removes the reference to the strings in Book2, allowing them to be garbage collected.s = s[:1]
General Rule
To avoid memory leaks, aim to zero out elements that refer to memory outside the slice's backing array.例如,具有指针,切片或其他复杂数据结构的字段的结构应在重新固定之前归零以切断外部参考。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3