Thursday, June 6, 2013

Stack Memory management in .Net

A Stack is a Last-In-First-Out data structure called shortly as LIFO. In .Net a Stack is used to store the details of variables and parameters which are used for executing a program. Stacks are used to store value types which include the built in types and structs.

In a Stack values keep get added one on top of the other, i.e the first object added to the stack goes to the bottom of the stack and the subsequent objects get added on top of the first object. Removing objects happens from the top of the stack, i.e the value which gets added at last to the stack will get removed first. Hence this is called a Last-In-First-Out (LIFO) data structure.

.Net runtime used the Stack data structure to store all primitive variables like int, string, bool etc and to store the programming execution sequence i.e the sequence in which methods get called.

Let us consider the following example.
A program execution starts by calling a method Main() in the program.
The Main() method of a program calls the method Method1().
Methods1() calls another methods Method2().

Here in this scenario when the program starts executing the details of the Main() method like local variables, current execution line etc will be stored at the bottom of the stack,

When the Main() method calls Method1(), a new stack frame is created and the details of Method1() are stored in the frame.

When Method1() calls Method2(), a new stack frame is created and the details of Method2() are stored in the frame.

When Method2() completes execution the entire details in the State frame created for Method2() will be popped (removed) from the stack and execution of Method1() will continue.

Similarly when Method1() completes execution the entire details in the State frame created for Method1() will be popped (removed) from the stack and execution of Main() will continue.

Finally when the Main() method completes execution its details are also removed from the Stack, now the stack becomes empty and there is no more code to be executed.

This is how program execution details and details of local variables and parameters are allocated and de-allocated by the .Net Framework runtime to manage memory.

Search Flipkart Products:
Flipkart.com

No comments: