I would like to understand how the stack variables are deallocated. Is it garbage collected as variables located on heap, or like C languages which after leaving the variable scope it will be deallocated internally ?
Asked
Active
Viewed 454 times
-1
-
Yees, but that's not i meant when i talked about C. Now i rewrote the question for better comprehension. Thank you for that point – Igor Barbosa Mar 16 '20 at 11:45
1 Answers
0
A variable allocated on the stack will be removed once the function allocating that variable returns because the stack pointer will be restored to its state before the function call. There is no GC involvement there.
In Go, if the stack variable is a pointer to an object on the heap, then once the function returns, the pointer will be removed, and then the GC can remove the object it was pointing to provided no other references exist.

Burak Serdar
- 46,455
- 3
- 40
- 59
-
1The second paragraph only applies to languages that admit GC (which does not include C). – R.. GitHub STOP HELPING ICE Mar 13 '20 at 21:28
-
True, however, the way I read the question, "...such as C" applies to the "after leaving..." part and not "..garbage collected.." part of the sentence. – Burak Serdar Mar 13 '20 at 21:46
-
Indeed I don't think the answer is wrong, just slightly unclear on that point. – R.. GitHub STOP HELPING ICE Mar 13 '20 at 21:59
-
What about a function returning a pointer that references a function value? This value will not be reclaimed off the stack long as the caller keeps the reference. – colm.anseo Mar 14 '20 at 00:00
-
1@colminator, Speaking for Go: It does escape analysis. Any variable whose address escapes the function will not be allocated on the stack, it will be allocated in heap. – Burak Serdar Mar 14 '20 at 03:28
-
Thank you @BurakSerdar that was what i ask for. Sorry for the lack of clarity of the question, now i rewrote the question. – Igor Barbosa Mar 16 '20 at 11:52