理解內存洩漏在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