1
votes

Today, I have read a blog on CodeProject about Memory management .NET.

URL - Article

It says -

Exiting the method (the fun): Now finally the execution control starts exiting the method. When it passes the end control, it clears all the memory variables which are assigned on stack. In other words all variables which are related to int data type are de-allocated in ‘LIFO’ fashion from the stack.

The big catch – It did not de-allocate the heap memory. This memory will be later de-allocated by the garbage collector.

As per my understanding, Garbage collector only de-allocate the Heap memory. So, who will de-allocate the stack memory?

Please suggest.

3
By default, the callee is responsible for cleaning the stack (stdcall calling convention). - Frédéric Hamidi
Codeproject.com content is not subject to any kind of decent review. Lots of nonsense and bugs because of that, including the first paragraph of this quote. Nothing is "cleared" or "deallocated", local variables are simple forgotten when the method returns. Not unlike the way the .NET Stack<> class works btw. - Hans Passant

3 Answers

2
votes

Values on the stack are automatically managed even without garbage collection because items are added and removed from the stack in a LIFO fashion every time you enter/exit a scope (be it a method or a statement), which is precisely why variables defined within a for loop or if statement aren’t available outside that scope.

You will receive a StackOverflowException when you’ve used up all the available space on the stack, though it’s almost certainly the symptom of an infinite loop (bug!) or poorly designed system which involves near-endless recursive calls.

0
votes

In short:

The stackmemory isn't deallocated. It's one block of memory that will be reused. Each time a scope declared variables (pushed onto the stack), it will be popped when the scope exits.

So when a method is called, the parameters (a value or a reference pointer) are pushed (copied) onto the stack and popped from it, when the method ends. (popping is just adjusting a pointer (index) with the memory)

That's why variables declared within the { } aren't available behind de }

This chunk of memory is per thread.

0
votes

In .NET, a variable is located on the stack, regardless of whether it holds a number (a value type), a struct (located entirely on the stack), or a reference to an object (i.e. the managed address of the object, where the object itself is located on the heap).

Also, people sometimes confuse variables with class fields. Fields, and all class members, are located on the heap, inside the area allocated when the object was instantiated.

So, there are no allocations or deallocations of any variables, since they are just values which go out of scope. After the variable goes out of scope, the GC cannot reach the actual (heap) object and it collects it eventually.