Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a garbage collector collect stack memory, heap memory, or both?

I read lot of articles about garbage collection and almost all article tells about heap memory. so my question is "garbage collection collects stack memory or heap memory or both".

like image 527
kalpesh Avatar asked Mar 26 '10 16:03

kalpesh


2 Answers

It collects heap memory. Usually, stack memory is collected automatically when the execution path reaches the end of the scope. e.g.:

void fun()
{
  int n; // reservation on the stack as part of the activation record
  ...
} // returning the stack pointer to where it was before entering the scope

In fact, in a language like C++, stack allocated variables are called auto variables.

like image 60
Khaled Alshaya Avatar answered Sep 27 '22 23:09

Khaled Alshaya


Heap memory.

Garbage collection is a method of deallocating memory that isn't being used anymore. Sometimes the "isn't being used anymore" part is tricky. With the stack, as soon as a function returns, we can be confident (excepting programmer error) that the local variables aren't being used anymore, so they are deallocated automatically at that time in nearly every language/runtime.

like image 29
Frank Schmitt Avatar answered Sep 27 '22 23:09

Frank Schmitt