Hacker News new | ask | show | jobs
by catlifeonmars 1892 days ago
I’m not sure I understood this correctly. Does the following allocate (on the heap)?

    foo := MyStruct{}
2 comments

No, that does not cause a heap allocation on its own. If other lines of code in that function caused a pointer to that value to escape the lifetime of the current function's stack frame, the compiler would determine that it has to be heap allocated instead.

I believe the person you are replying to was making a confusing point about some hand wavy notion of "any kind of allocation", which includes stack allocations... which are determined at compile time, not with "alloca".

Ah, that makes much more sense!
No. In this case foo will live on the stack (unless you take its address later).

  foo := MyStruct{} // Could live on the stack
  _ := &foo // Oh, now foo must live on the heap.
This isn't even true.

No matter what syntax you write inside a function, the Go compiler always has the final say on what is stack allocated and what is heap allocated. Taking the address of foo will not cause foo to be heap allocated unless Go is unable to prove that the pointer will live for less time than the current stack frame. Look up "escape analysis".

Basically the only way to guarantee that something will always be heap allocated is to assign it to a global variable. Even returning a pointer to that object from the current function is not a strong guarantee, since the compiler could inline this function into the caller and determine that everything can live happily inside the newly inlined stack frame without heap allocation.

Good point. It isn't "must", I should have said "may".