Saturday 27 December 2014

Stack Vs Heap Memory in C

Memory is one of the various resources on computer system and this needs to be managed efficiently for smooth
executions of both user and system programs.
Memory mainly consists of two portions. Stack and Heap.
Stack frame is implemented using stack data structure and is used for storing local variables and function calls.
This memory portion is static and do not grow while the program is running.
When program execution starts OS assigns fix amount of space for stack. If local variables and function calls grow
more than this specified amount we tend to see stack overflow errors and program will crash.
One common case when this can happen is in case of bad regression.
Stack is a LIFO data structure. That means the element which is written last is read or manipulated first. In other
words the data which is pushed recently is read first and the function which is pushed recently is manipulated first.
Allocation and DE allocation in stack happens through two operations push and pop.
PUSH - Add item to stack (Top)
POP - Remove item from stack (Top)
If we need to declare a large data type like array as local variable we need to know the size of the array at
compile time.
Heap on the other hand does not have anything to do with heap data structure as we study in data structures. Heap is
also called dynamic memory. Using heap is also known as dynamic memory allocation.
Its size can vary during run time of program as far as we don't run out of memory of the system. Heap is
implemented in different ways depending on operating systems.
How to use Heap in C:
1) malloc
2) calloc
3) realloc
4) free


 

No comments:

Post a Comment