Allocation of the Stack memory in .NET

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.


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.


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 (ie 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.

链接地址: http://www.djcxy.com/p/13874.html

上一篇: 什么是更高效的堆栈内存或堆?

下一篇: .NET中堆栈内存的分配