13

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sergey
  • 11,548
  • 24
  • 76
  • 113

1 Answers1

13

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

Frank
  • 2,738
  • 19
  • 30