Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value types in object stored in heap as well?

I can imagine this question has been asked thousands of times, but I didn't have much luck in finding the answer, plus this is more out of curiosity than need.

Digging into the nuts and bolts of C#, I was wondering since objects are stored in the heap, are the value types within the objects stored in the heap as well or are they placed in the stack?

like image 695
BoredOfBinary Avatar asked Jan 18 '11 18:01

BoredOfBinary


People also ask

Can value types be stored in heap?

Note that a value type can be stored in a stack frame, in the CPU register or even in the heap memory if the value type is contained inside an object, i.e., if it is a part of a reference type.

Are value types stored on the stack or heap?

Reference Type variables are stored in the heap while Value Type variables are stored in the stack. Value Type: A Value Type stores its contents in memory allocated on the stack. When you created a Value Type, a single space in memory is allocated to store the value and that variable directly holds a value.

What kind of data is stored in heap?

Heap memory is a Dynamic memory(its size changes as program run) used to store arrays, global variables(with global scope/accessible from any function) and any created class instances(objects) at runtime in Java which are referred by the reference variables from Stack memory.

Can object data be stored in heap?

Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.


2 Answers

Andrew Hare is right. For the full details, see Eric Lippert's blog entry:

I'm disturbed by the myth that "value types go on the stack" ... It is usually stated incorrectly: the statement should be "value types can be stored on the stack", instead of the more common "value types are always stored on the stack".

like image 69
Rich Tebb Avatar answered Sep 28 '22 21:09

Rich Tebb


They are stored in the heap, inside of the memory allocated for the reference type. In addition, value types are often stored in places other than "the stack". However, the CLI spec does not specify where the memory pool that stores value types resides - it's an implementation detail that should not matter.

like image 45
Reed Copsey Avatar answered Sep 28 '22 22:09

Reed Copsey