When is a variable allocated on the stack, and when on the heap? Any GC difference?

If a function returns a struct, that struct will be on the stack. If it returns a pointer to a struct, that stucture allocation will be on the heap ?

I am feeling confused here, is there a defenitive tutorial a bout where a new variable will be allocated ?

Also, is there any difference regarding garbage collection, between a stack and a heap allocated variable ? How are stack variables (method calls) being garbage collected ? Is there some special case there

As far as I understand, the struct allocation is always on heap whenever pointer value is requested, inside or outside function.

Link: https://stackoverflow.com/questions/10866195/stack-vs-heap-allocation-of-structs-in-go-and-how-they-relate-to-garbage-collec (see PeterSO’s disassembly answer first and then the accepted Sonia’s disassembly).

What you’re really interested in is CALL ,runtime.new+0(SB) where the binary is calling the heap allocation.

Is this Go 101 manual sufficient? https://go101.org/article/memory-block.html


I’m including go disassembler guide just in case you need it in your exploration: https://www.grant.pizza/dissecting-go-binaries/.

2 Likes

@JOhn_Stuart, has my post be sufficient enough to answer this question? If it does, please “marked as solved”. Let me know if you need to proceed further.

2 Likes

Bill Kennedy wrote a short series of articles about this that made it comprehensible to me. It sounds like you have the gist of it.

As I recall, there are basically two instances when an escape to the heap will occur:

  • A pointer returned from a function/method will escape to the heap (unless there are some build flags included) because its memory location exists outside of the main memory of the stack.

  • A value assigned to an interface will also escape to the heap because memory cannot be adequately allocated to an interface variable since it could vary dramatically.

2 Likes

Hi @hollowaykeanho,
How can I mark this question as solved ?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.