Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning pointer from a local variable in function

Tags:

pointers

go

I'm reading a book called The Go Programming Language, and in the 2nd chapter about pointers the following is written

It is perfectly safe for a function to return the address of a local variable. For instance, in the code below, the local variable v created by this particular call to f will remain in existence even after the call has returned, and the pointer p will still refer to it:

var p = f()
func f() *int {
    v := 1
    return &v
}

I totally don't get this, a local variable is supposed to be destroyed after the function execution. Is it because maybe v is allocated on the heap. I know in C if you allocate space using malloc it won't be destroyed after function execution because it's on the heap.

like image 267
Danilo Gacevic Avatar asked Dec 14 '22 14:12

Danilo Gacevic


1 Answers

Go isn't C. Despite similarities, it is much higher-level. It utilizes a complete runtime with a green thread scheduler and garbage-collecting memory manager. It will never collect memory so long as it has live references.

The Go compiler includes a stage called "escape analysis", where it tracks each variable to see if it "escapes" the function in which it is declared. Any value that can escape is allocated on the heap and managed by garbage collection; otherwise, it is (usually) allocated on the stack.

You can find more information on the subject:

  • https://blog.golang.org/ismmkeynote
  • https://dave.cheney.net/2014/06/07/five-things-that-make-go-fast
  • https://dougrichardson.org/2016/01/23/go-memory-allocations.html
  • https://www.agardner.me/golang/garbage/collection/gc/escape/analysis/2015/10/18/go-escape-analysis.html
  • https://www.ardanlabs.com/blog/2017/05/language-mechanics-on-escape-analysis.html
like image 62
Adrian Avatar answered Dec 16 '22 03:12

Adrian