I have encountered strange (as for a man who is new to golang) behaviour of my goroutine:
go func(...) {
for {
buffer := make([]byte, 1024)
...
}
}
It slowly eats RAM. I understand that it is caused by calling make
in an endless loop; it just allocates new memory every time. But i don't quite get why this construction:
var buffer []byte
for {
buffer = make([]byte, 1024)
...
}
}
..works well, while the first one doesn't. Shouldn't garbage collector detect that memory which old buf
was pointing at is unreachable in both cases? And maybe there are some other similar traps that a go-newbie should know?
Also, if i will return this goroutine, will leaked memory be freed?
UPD: full memory leaking routine code:
go func(dataChannel chan []byte, errorChannel chan error) {
for {
buf := make([]byte, 1024)
_, err := conn.Read(buf)
if err != nil {
errorChannel<- err
break
}
dataChannel<- buf
}
} (dataChannel, errorChannel)