14

I am new to Go, and found it is OK to return the address of a local variable defined in a function. That is obviously not possible in C since local variable is in stack.

So I am just wondering why it is OK to do it in Go? In Go, the local variable is in heap? Will it affect performance since allocating heap memory is quite expensive than stack? Is it possible allocate local variable in stack in Go? Or actually is there stack memory in Go?

icza
  • 389,944
  • 63
  • 907
  • 827
Eric
  • 688
  • 1
  • 6
  • 17
  • 4
    Related: [Stack vs heap allocation of structs in Go, and how they relate to garbage collection](http://stackoverflow.com/questions/10866195/stack-vs-heap-allocation-of-structs-in-go-and-how-they-relate-to-garbage-collec) – icza Aug 03 '15 at 12:14
  • In Pascal, C et. al. the scope of a variable and it’s lifetime are tighly coupled. All local variables function are allocated on stack and invalidated after termination of the scope. In Golang this does nomore hold. E.g. localness can be broken up by pointer references. Thus a local variable can be return as a pointer reference, and it survives termination of the local scope. This idea may be suspicious to many programmers of PASCAL or C-style languages. Thus thinking about this question can greatly help to understand Golang specifics. – olippuner Sep 24 '20 at 23:01

1 Answers1

25

There's a very clear answer to that question in the FAQ:

How do I know whether a variable is allocated on the heap or the stack?

From a correctness standpoint, you don't need to know. Each variable in Go exists as long as there are references to it. The storage location chosen by the implementation is irrelevant to the semantics of the language.

The storage location does have an effect on writing efficient programs. When possible, the Go compilers will allocate variables that are local to a function in that function's stack frame. However, if the compiler cannot prove that the variable is not referenced after the function returns, then the compiler must allocate the variable on the garbage-collected heap to avoid dangling pointer errors. Also, if a local variable is very large, it might make more sense to store it on the heap rather than the stack.

In the current compilers, if a variable has its address taken, that variable is a candidate for allocation on the heap. However, a basic escape analysis recognizes some cases when such variables will not live past the return from the function and can reside on the stack.

TLDR: You shouldn't care. Go takes care of allocation for you.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758