4
votes

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.

1
Go is not C. Go has a garbage collector that manages memory for you. - peterSO
"local" variables don't work the same way in Go as they do in C. Whether a variable is allocated on the stack or the heap is determined by the compiler at compile time based on escape analysis, not just based on whether it's a pointer or not (as it is in C). Generally speaking, you can simply trust Go's garbage collector. It'll manage memory for you, and the language usually prevents situations where you could access a stale pointer or unallocated memory (segfaults in Go generally come from trying to access a nil pointer). - Kaedys
Accessing a nil pointer shouldn't ever segfault, but it will trigger a panic. - Adrian
SIGSEGV is in fact considered as a segmentation fault, or the fault caused by invalid memory reference no matter how you call it. - Berkant Ipek
Local refers to the scope of a variable, not how the value is allocated. The spec is silent on the details of allocation for all variables. - Cerise Limón

1 Answers

12
votes

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: