I've started to learn Go, and found something I'm not able to find info about.
For example, if I'm making my own list structure
type elem struct {
prev *elem
next *elem
value string
}
And adding new elements to it with
Current.next = &elem{}
How should I remove them? I mean, how can I remove data of elem from memory, not just from the list?
Memory leaks are very common in almost any language, including garbage collected languages. Go is not an exception. A reference to an object, if not properly managed, may be left assigned even if unused. This usually happens on an application logic level, but can also be an issue inside of an imported package.
If you really want to manually manage memory with Go, implement your own memory allocator based on syscall. Mmap or cgo malloc/free. Disabling GC for extended period of time is generally a bad solution for a concurrent language like Go. And Go's GC will only be better down the road.
In Go dynamic memory block is allocated mainly using new and make. New allocates exact one memory block that is used to create struct type value, whereas, make creates more than one memory block and returns the reference, like a slice, map or channel value.
Go has garbage collection. It will scan for data that has no pointer to it and remove it from heap (Garbage collector is running beside your program). The only thing you should do is:
Current.next = nil
Your elem{}
will be removed from memory eventually after you remove all pointers to it (It's not deterministic. Can't tell exactly when elem{}
will be released). There are different implementations of garbage collection; Go's implementation may change at any time.
If Current
goes out of scope, you don't even need to set next
to nil
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With