Tuesday, February 14, 2012

Static Vs dynamic allocation in C

Memory allocation: This depends on the programming language that you are using. I am giving here for C programming language.

Static memory allocation: This allocation also called as compile time allocation, as allocation will happen at the time of compilation.Stack segment memory will be used for this allocation. There wont be any memory leak in this allocation.

  • No memory leaks
  • allocated memory is available till the end
  • No need of freeing the allocated memory, it will be freed automatically.
  • There will be some memory wastage.
  • Not efficient.
e.g : array's, global variables, auto, static variables

Dynamic memory allocation : This allocation is also called as run time memory allocation as allocation will happen dynamically basing on requirement. Heap segment will be used for this allocation. Need to allocate the required amount of memory and need to free the allocated memory with out fail. for allocation and freeing there are special functions malloc, calloc, free in C and new , delete in C++. If you not freeing the allocated memory, there is a chance for memory leak.

  • Very efficient.
  • Uses less memory

  • Need to free the allocated memory
  • Memory leaks
  • Application may fail in run time

e.g : linked list, binary trees etc.

No comments:

Popular Posts