Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

pointers - Memory leak in golang slice

I just started learning go, while going through slice tricks, couple of points are very confusing. can any one help me to clarify.

To cut elements in slice its given

Approach 1:

a = append(a[:i], a[j:]...)

but there is a note given that it may cause to memory leaks if pointers are used and recommended way is

Approach 2:

copy(a[i:], a[j:])
for k, n := len(a)-j+i, len(a); k < n; k++ {
    a[k] = nil // or the zero value of T
}
a = a[:len(a)-j+i]

Can any one help me understand how memory leaks happen. I understood sub slice will be backed by the main array. My thought is irrespective of pointer or not we have to follow approach 2 always.

update after @icza and @Volker answer..

Lets say you have a struct

type Books struct {
    title   string
    author  string
}

var Book1 Books
var Book2 Books 

    /* book 1 specification */
    Book1.title = "Go Programming"
    Book1.author = "Mahesh Kumar"

    Book2.title = "Go Programming"
    Book2.author = "Mahesh Kumar"

    var bkSlice = []Books{Book1, Book2}
    var bkprtSlice = []*Books{&Book1, &Book2}

now doing

bkSlice = bkSlice[:1]

bkSlice still holds the Book2 in backing array which is still in memory and is not required to be. so do we need to do

bkSlice[1] = Books{}

so that it will be GCed. I understood pointers have to be nil-ed as the slice will hold unnecessary references to the objects outside backing array.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...