Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to free memory in go? [duplicate]

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?

like image 712
CrazyWu Avatar asked Dec 26 '17 13:12

CrazyWu


People also ask

Does Go have memory Leaks?

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.

Does Go have manual memory management?

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.

How do I allocate more memory to Go?

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.


1 Answers

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.

like image 200
Arman Ordookhani Avatar answered Sep 19 '22 17:09

Arman Ordookhani