Memory leak is, when there is unused memory in application and GC can collect it, normally it occurs if some where in application we keep unwanted strong reference of an object, and GC will able to find the path(Direct and indirect) so it can free this object, but this all are true about reference type that mean in Heap memory allocation.
But what about stack And as far i know GC will not responsible to clean up the stack it will automaticaly clean when function will return.
So my question is that Is there any chance that memory leak will occurs in stack also?, if yes then at what scenario and what are the best practices to avoid this kind of leak.
If you are writing recursive functions that keep stack-local references to large data that is not needed in sub-recursive calls, then this is a type of space leak, but it is very unusual to have this be a problem in practice.
More generally, if you have something like
then this is a kind of stack-space-leak, but again, it is unlikely in practice. The fix is easy:
In general, if you ever have a giant variable on the stack right before a call that will last ‘a long time’ and the variable is no longer used, you can null it out to ensure it can be GC’d before going into the ‘long’ call.
(It is possible that an optimizer may do this for you based on reachability analysis.)
Note that the above answer is for references to heap-allocated objects that are rooted on the stack. If, on the other hand, you have stack-allocated memory (e.g. a gigantic struct or stackalloc thingie), then the fix is not as easy, but this is even rarer in practice (who ever creates giant structs?).