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".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With