Wednesday, 20 December 2017

Dynamic Memory allocation C language

Memory is storage unit which every program need for their operation. When you run your program then a request is made to OS for memory allocation. There are two types of memory allocations are used in programming.
  • Static
  • Dynamic

Static memory allocation is fix allocation.  It cannot be change during run time. Static memory allocation is better option in case when we know exactly how much amount of memory need. For example holding roll number marks of student etc.


Static memory is allocated at compile time and automatically manages by compiler. But is another scenario? When a programmer doesn’t know that how much memory a program actually need. For example, in an online exam application you have not fix number of student appeared in examination. It will be fit by operator, so we don’t know compile time memory requirement. It will be decide at run time.


As we know everything has some pros and cons. Dynamic memory also has same thing. I will show to you this by comparing both in following table.

Static
Dynamic
Fast because no extra work has to done for memory allocation at compiler level because it is decided at compiles time.
To allocate memory at run time some routines call at run time which are time consuming.
Due to fix nature of memory allocation cannot be increase or rerelease at run time.
Due to flexibility of dynamic memory allocation it can be allocate and release at run time as required.
Good for Traversal point of view. Random traversal possible. Array allocate continuous memory So random traversal is takes place.
Not good for traversal point of view because dynamic calculation of address is not possible as in array. In link list only one direction of traversal is possible
Allocated memory is managed by compiler.
Allocated memory is managed by programmer.
Example : Array,Built in variable
Example : link list,tree,stack,queueetc