Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack and heap in c# [duplicate]

Possible Duplicate:
What and where are the stack and heap

There is a difference in C# between heap and stack. I've just realized that I always thought that stack is RAM and heap is 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?

like image 778
Sergey Avatar asked Jun 30 '11 07:06

Sergey


People also ask

What is the main difference between stack and heap?

Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution. Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it.

What is heap in C?

In certain programming languages including C and Pascal , a heap is an area of pre-reserved computer main storage ( memory ) that a program process can use to store data in some variable amount that won't be known until the program is running.

What is stack memory in C?

The stack is a special region of memory, and automatically managed by the CPU – so you don't have to allocate or deallocate memory. Stack memory is divided into successive frames where each time a function is called, it allocates itself a fresh stack frame.

Does C have heap?

Data Storage In all C and C++ code, nearly all of your data is stored in only one of two types of memory storage: All variables allocated by malloc (or new in C++) is stored in heap memory. When malloc is called, the pointer that returns from malloc will always be a pointer to “heap memory”.


1 Answers

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

like image 186
Frank Avatar answered Sep 20 '22 15:09

Frank