Firstly, I'm currently working in C# and I've been reading up on memory management. So far, I've read through some great answers on stack overflow explaining the difference between stack memory and the managed heap memory. The majority of the answers state that by declaring:
int x = 5, you're allocating enough memory for the type of x within the stack memory.
I understand how this works as well as the scope of it, however when I read the explanation of heap memory, it confused me.
If you're saying int x = 5, since int is an alias of System.Int32, wouldn't x technically be a pointer to a new instance of the System.Int32 struct? And if so, wouldn't it then be stored in the heap memory since that's used for instance objects.
In this tutorial, it states (for the line class1 cls1 = new class1()):
... creates a pointer on the stack and the actual object is stored in a different type of memory location called ‘Heap’.
By this logic, isn't everything stored on the heap and only pointers stored on the stack? Examples being new instances of
System.String, System.Int64, System.Boolean, System.Decimal etc.I thought I understood it, however clearly I don't, so I would appreciate someone explaining whether the stack is only for pointers or which part I've misinterpreted. Thanks in advance.
System.Int32is a struct, not a class. So, as a local, it will likely get allocated on the stack.