This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What and where are the stack and heap
There is a difference in C# between the heap and stack. I've just realized that I always thought that the stack is RAM and the heap is a hard drive. But now I'm not sure if it's correct. If it isn't, then what's is the difference if they are stored in one place?
"The stack" (or more precisely the call stack) is automatically managed memory (even in "unmanaged languages" like C): Local variables are stored on the stack in stack frames that also contain the procedures or functions arguments and the return address and maybe some machine-specific state that needs to be restored upon return.
Heap memory is that part of RAM (or rather: virtual address space) used to satisfy dynamic memory allocations (malloc in C).
Yet, in C# heap and stack usage is an implementation detail. In practice though, objects of reference type are heap-allocated; value type data can both be stored on the stack and on the heap, depending on the context (e.g. if it's part of an reference-type object).
Related
This question already has answers here:
Why don't structs support inheritance?
(10 answers)
Closed 9 years ago.
I am reading CLR via C# by Jeffery Richter and it says a struct is a value type and cannot be inherited.
Are there any technical or philosophical reasons?
ADD 1 - 5:53 PM 11/11/2020
Every decision, no matter how reasonable or accidental it may look, has its impact, subtle or profound. We try to decouple things, sometimes by creating new coupling...
Edit: There are serious editorial concerns about this post, apparently. See comment section.
A little of both.
Philosophically, it works out - there are classes, which are the "real" building block for object oriented programming, and there are structs, which are lightweight data types for storage but allow object-like method calls for familiarity and convenience.
Technically, being a "value type" means that the entire struct - all of its contents - are (usually) stored wherever you have a variable or member of that type. As a local variable or function parameter, that means on the stack. For member variables, that means stored entirely as part of the object.
As a (primary) example of why inheritance is a problem, consider how storage is affected at a low level if you allowed structs to have subtypes with more members. Anything storing that struct type would take up a variable amount of memory based on which subtype it ended up containing, which would be an allocation nightmare. An object of a given class would no longer have a constant, known size at compile time and the same would be true for stack frames of any method call. This does not happen for objects, which have storage allocated on the heap and instead have constant-sized references to that storage on the stack or inside other objects.
This is just an intuitive, high-level explanation - See comments and other answers for both expanded and more precise information.
Edit: The link in the comments to Eric Lippert's article The Stack Is An Implementation Detail, is now located on his personal blog site.
Because it is the way structs are represented in .NET. They are value types and value types don't have a method table pointer allowing inheritance.
You may find the answers to SO Question Why are .NET value types sealed? relevant. In it, #logicnp refers to ECMA 335, which states:
8.9.10 Value type inheritance
[...]
Will be sealed to avoid dealing with the complications of value slicing.
The more restrictive rules specified here allow for more efficient implementation without severely compromising functionality.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
int[] age=new int[5];
After reading many posts and blogs ,I am still not clear about the fact why arrays are reference types.I know this question is like very old and have been asked plenty times but still couldnt find direct answer.
Known things :Since Arrays are allocated on heap,hence they are reference types .
Need to know:Whats the reason behind making(compiler) arrays as reference types?.
Suppose age[0]=5,age[1]=25 ,what is the difficulty in assigning these on stack or make reference to heap if their type was object.why consider heap as accessing time is slow comparatively?.
Why heap ,why not on stack like for structures?.
Several reasons:
value types are passed by value (as in copied). So if you called a method with a value-type array, you'd be copying all the contents.
Stack memory is limited and primarily designed for quick access to parameters that are in current use (as implied by the term stack). Putting a large object onto the stack would cause lookups of other local state to take much longer, because they wouldn't all be on the same cache line in the CPU cache anymore.
Array contents are modifiable. So you'd have all the issues that you have with mutable structs when you tried to set a value, only to find that the copy, not the "original" was modified.
EDIT:
Yes you can use stackalloc in unsafe code. Doesn't make it a good idea.
This question already has answers here:
Why are structs stored on the stack while classes get stored on the heap(.NET)?
(10 answers)
Closed 5 years ago.
I heard that variables are stored in stack and objects are stored in heap.
If i declare variable as var password= "abc".Now where this password is going to store(heap /stack)
Where an object is stored is not something you should be worrying about in the general case, but, as everytime this question crops up in SO, commentaries and answers crop up spreading the mythical and false belief that value types are stored in the stack and reference types are stored in the heap. No, no and no!
Thnink of it this way, its better: reference types go on the heap, short lived value types go on the stack. Long lived value types (fields, captured variables in a closure) go on the heap. The storage mechanism has very much to do with the expected lifetime of a variable, its not all about the nature of the type of the variable.
If you really want to know the details, read this.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Where are .NET local variables stored?
function storeonstack()
{
int a;
int b;
int c;
a=1;
b=1;
a=2
c=2;
}
Can Some body explain me how these value types are stored on stack?
Practically speaking*, value types are stored on the stack if they are local variables within a method, or on the heap if they are members of a reference type. Sometimes, local variables may also be stored on the heap if they are included in a closure. This is required so that the variables can continue to live after the function exits (and the stack frame is cleaned up). Local variables may also be stored in registers when they are used in operations, before being spilled back to the stack. Depending on JIT optimizations, local variables may only exist in registers, or may not exist at all. Member variables should always exist, though.
*Yes, technically, there's no guarantee that things like stack and heap exist, but let's be honest, on most, if not all, .NET implementations, there is a stack and a heap as in C programs.
It is an implementation detail and depends upon compiler. It may vary from compiler to compiler.
The Truth About Value Types
The stack is an implementation detail
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have read a lot of .NET performance articles that describe Gen1,Gen2 garbage collection and objects surviving the generations.
Why does objects survives the collection?
What is pinning?
One reason you have multiple generations in a garbage collector is to avoid losing memory to fragmentation.
Every function call can mean the creation and deletion collection of multiple objects, and so the memory heap for your program tends to fragment very quickly. This leaves holes behind that aren't very usable. The result is that your program needs to be periodically de-fragmented, just like a hard disk. This is part of what happens during a collection.
When an object survives a collection, it is moved to a longer-lived generation on the theory that if it survived one collection it will probably survive others. Thus the later generations have less turn-over and don't fragment as much. This means your program spends less time overall juggling things around to clean up holes and wastes less memory. This is also an improvement over traditional memory management (malloc/free or new/delete), which left it up to the operating system to manage any memory fragmentation.
The reason an object survives collection is because there is something somewhere that is still "in scope" and holds a reference to that object. There are a few ways you can cause this to happen and then forget about the reference, so it is possible to "leak" memory in managed code.
Sometimes people are tempted to call GC.Collect() in an effort to get the garbage collector to clean something up. Perhaps they've discovered they have a leak, or think memory is becoming over-fragmented. You should resist those urges. While garbage collection in .Net is not perfect, is it very good, and it's almost certainly much better at cleaning up memory than you are. Odds are that if an object can and should be collected, it will be. Remember that calling GC.Collect() can actually make things worse by helping the garbage collector move objects up to a higher generation, and thus keeping them around for longer than they otherwise would be.
Instead, if you suspect you have a leak, look to your own code for something like a global or static variable that might hold a reference to a lot of other items. The only time you should call GC.Collect() is when you have information about the nature of the program that is not available to the garbage collector, and that's pretty rare as the GC knows every reference you've created.
"Pinning" is for when you need to pass an object to an unmanaged library. The garbage collector can move an object's physical location in memory, and so you need to "pin" it in one place or the pointer used by the unmanaged library could become invalid. A pinned object cannot be collected, and so you shouldn't pin an object for any longer than necessary.
http://blogs.msdn.com/maoni/ is a good resource.
Asking questions here helps too :)
For your questions:
Why do objects survive the collection:
Objects survive a collection when they are "live objects", or "Reachable objects". Reachable objects are objects where there is a reference to them from another object that is on:
The stack
The finalization queue
another object in a higher generation ( for example a Gen2 Object holding a reference to a Gen0 Object )
The handle table ( a data structure used by the CLR, and require a seperate post on its own:) )
What is Pinning:
Pinning means making sure the object doesn't move in memory. objects move in memory as a result of a compacting GC, you can create a GCHandle of typed pinned if you want to pin an object, pinning also happens automatically behind the sciene for objects that are passed to native code via PInvoke ( like strings that are passed as output, the internal buffer gets pinned during the call to PInvoke ).
Check out http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.gchandle.aspx for a good example about GCHandle.
Pinning is used to keep the garbage collector from relocating objects. It can hurt performance by restricting what the garbage collector can do. In general pinned objects should be pinned for as short as time as possible.