内存分配: 堆栈还是堆?

我对 堆栈 VS 堆之间的内存分配基本知识感到困惑。根据标准定义(每个人都会说的东西) ,所有的 值类型将被分配到 Stack,而 参考文献类型将被分配到

现在考虑下面的例子:

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


class Program
{
static void Main(string[] args)
{
MyClass m = new MyClass();
}
}

现在,在 c # 中如何进行内存分配?MyClass(即 m)的对象是否将完全分配给堆?也就是说,int myIntstring myString都会堆起来?

或者,对象将被分成两部分,并被分配给两个内存位置,即 Stack 和 Heap?

66718 次浏览

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).

You should consider the question of where objects get allocated as an implementation detail. It does not matter to you exactly where the bits of an object are stored. It may matter whether an object is a reference type or a value type, but you don't have to worry about where it will be stored until you start having to optimize garbage collection behavior.

While reference types are always allocated on the heap in current implementations, value types may be allocated on the stack -- but aren't necessarily. A value type is only allocated on the stack when it is an unboxed non-escaping local or temporary variable that is not contained within a reference type and not allocated in a register.

  • If a value type is part of a class (as in your example), it will end up on the heap.
  • If it's boxed, it will end up on the heap.
  • If it's in an array, it will end up on the heap.
  • If it's a static variable, it will end up on the heap.
  • If it's captured by a closure, it will end up on the heap.
  • If it's used in an iterator or async block, it will end up on the heap.
  • If it's created by unsafe or unmanaged code, it could be allocated in any type of data structure (not necessarily a stack or a heap).

Is there anything I missed?

Of course, I would be remiss if I didn't link to Eric Lippert's posts on the topic:

"All VALUE Types will get allocated to Stack" is very, very wrong; struct variables can live on the stack, as method variables. However, fields on a type live with that type. If a field's declaring type is a class, the values are on the heap as part of that object. If a field's declaring type is a struct, the fields are part of that struct where-ever that struct lives.

Even method variables can be on the heap, if they are captured (lambda/anon-method), or part of (for example) an iterator block.

simple measures

Value type can be stred on THE STACK ,it is the implementaional detail it can be allocated to the some futuristist data structure.

so, it is better to understand how value and reference type works , Value type will be copied by value that means when you pass a value type as a param to a FUNCTION than it will be copied by nature means you will have a total new copy.

Reference types are passed by reference ( againg do not consider reference will store a address again in some future versions ,it may be stored on some other data structures.)

so in your case

myInt is a int which is ecapsulated in a class which offcourse an reference type so it will be tied to the instance of the class which will be stored on 'THE HEAP'.

i would suggest , you can start reading blogs written by ERIC LIPPERTS.

Eric's Blog

Each time an object is created in it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables . In methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed. In a multithreaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is threadsafe (each thread will have its own stack) but the heap is not thread safe unless guarded with synchronisation through your code.

This link is also useful http://www.programmerinterview.com/index.php/data-structures/difference-between-stack-and-heap/

Stack

The stack is a block of memory for storing local variables and parameters. The stack logically grows and shrinks as a function is entered and exited.

Consider the following method:

public static int Factorial (int x)
{
if (x == 0)
{
return 1;
}


return x * Factorial (x - 1);
}

This method is recursive, meaning that it calls itself. Each time the method is entered, a new int is allocated on the stack, and each time the method exits, the int is deallocated.


Heap

  • The heap is a block of memory in which objects (i.e., reference-type instances) reside. Whenever a new object is created, it is allocated on the heap, and a reference to that object is returned. During a program’s execution, the heap starts filling up as new objects are created. The runtime has a garbage collector that periodically deallocates objects from the heap, so your program does not run Out Of Memory. An object is eligible for deallocation as soon as it’s not referenced by anything that’s itself alive.
  • The heap also stores static fields. Unlike objects allocated on the heap (which can get garbage-collected), these live until the application domain is torn down.

Consider the following method:

using System;
using System.Text;


class Test
{
public static void Main()
{
StringBuilder ref1 = new StringBuilder ("object1");
Console.WriteLine (ref1);
// The StringBuilder referenced by ref1 is now eligible for GC.


StringBuilder ref2 = new StringBuilder ("object2");
StringBuilder ref3 = ref2;
// The StringBuilder referenced by ref2 is NOT yet eligible for GC.
Console.WriteLine (ref3); // object2
}
}

In the above example, we start by creating a StringBuilder object referenced by the variable ref1, and then write out its content. That StringBuilder object is then immediately eligible for garbage collection, because nothing subsequently uses it. Then, we create another StringBuilder referenced by variable ref2, and copy that reference to ref3. Even though ref2 is not used after that point, ref3 keeps the same StringBuilder object alive—ensuring that it doesn’t become eligible for collection until we’ve finished using ref3.

Value-type instances (and object references) live wherever the variable was declared. If the instance was declared as a field within a class type, or as an array element, that instance lives on the heap.

m is a reference to an object of MyClass so m is stores in the stack of main thread but the object of MyClass stores in the heap. Therefore myInt and myString store in the heap. Note that m is only a reference (an address to memory) and is on main stack. when m deallocated then GC clear the MyClass object from the heap For more detail read all four parts of this article https://www.c-sharpcorner.com/article/C-Sharp-heaping-vs-stacking-in-net-part-i/

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.

This is wrong. Only local (in the context of a function) value types/arrays of value types are allocated on the stack. Everything else is allocated on the heap.