stack vs heap

Stack [ local variable]

-Variable like int, char, float are store in stack.(Complex structures also array,struct)

-What is – stack is special region in computer memory, its stores temporary variables created by each function, stack is FILO (first in last out)

-Every time a function declare a new variable it pushed into stack, when function exits pushed elements are freed(pop), once stack variables are freed , that region of memory available for other stack variable

-Memory managed (Allocation and free) by CPU efficiently, also read and write stack is very fast

-Keep in mind the stack memory region also limited by varies on OS,

Heap [Global Variable]

-Heap region memory not managed by CPU, it is free floating region of memory (larger), in ‘C language’ use malloc, calloc to allocate memory,realloc to reallocate the memory, once we allocated we need to free up if not used then only other process takes the memory when not in use, if we fail to  do this memory leak problem occur

When to use

-if u need large block of memory, and access variable globally by any function then use Heap

 

 

Ref: http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html

Leave a comment