Thursday, 8 September 2016

c# - Memory allocation: Stack vs Heap?



I am getting confused with memory allocation basics between Stack vs Heap. As per the standard definition (things which everybody says), all Value Types will get allocated onto a Stack and Reference Types will go into the Heap.



Now consider the following example:




class MyClass
{
int myInt = 0;
string myString = "Something";
}

class Program
{
static void Main(string[] args)

{
MyClass m = new MyClass();
}
}


Now, how does the memory allocation will happen in c#? Will the object of MyClass (that is, m) will be completely allocated to the Heap? That is, int myInt and string myString both will go to heap?



Or, the object will be divided into two parts and will be allocated to both of the memory locations that is, Stack and Heap?


Answer




m is allocated on the heap, and that includes myInt. The situations where primitive types (and structs) are allocated on the stack is during method invocation, which allocates room for local variables on the stack (because it's faster). For example:



class MyClass
{
int myInt = 0;

string myString = "Something";

void Foo(int x, int y) {
int rv = x + y + myInt;

myInt = 2^rv;
}
}


rv, x, y will all be on the stack. myInt is somewhere on the heap (and must be access via the this pointer).


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...