Difference Between Static and Dynamic Memory Allocation

Difference Between Static and Dynamic Memory Allocation in C

Comparison between Static and Dynamic Memory Allocation

The key difference between Static and Dynamic Memory Allocation is that in Static Memory Allocation memory is allocated at Compile Time, once the memory is allocated, the memory size is fixed can not be changed. In Dynamic Memory Allocation memory is allocated at runtime using calloc(), malloc(), once the memory is allocated, the memory size can be changed.

Comparison Between Static and Dynamic Memory Allocation
Comparison Between Static and Dynamic Memory Allocation

Comparison Chart

Static Memory Allocation Dynamic Memory Allocation
Static Memory Allocation memory is allocated at compile time. Dynamic Memory Allocation memory is allocated at run time.
Memory can not be Changed while executing a program. memory can be Changed while executing a program.
Used in an array. Used in the linked list.
It is fast and saves running time. It is a bit slow.
It allocates memory from the stack. It allocates memory from the heap
Allocated memory stays from start to end of the program. Memory can be allocated at any time and can be released at any time.
It is less efficient than the Dynamic allocation strategy. It is more efficient than the Static allocation strategy.
Implementation of this type of allocation is simple. Implementation of this type of allocation is complicated.
Example:
int i;
float j;
Example:
p = malloc(sizeof(int));




Static Memory Allocation

  • Static memory allocation, the allocated memory is fixed. Once the memory is allocated, it cannot be changed. The memory cannot be increased or decreased.
  • In C, static memory can be allocated using the static keyword.
static int a = 32;

Dynamic Memory Allocation

  • Dynamic Memory Allocation memory is allocated at runtime, once the memory is allocated, the memory size can be changed.
  • There are 4 types of dynamic memory allocation functions
    • malloc()
    • calloc()
    • realloc()
    • free()
Function
Syntax
malloc () malloc (number *sizeof(int));
calloc () calloc (number, sizeof(int));
realloc () realloc (pointer_name, number * sizeof(int));
free () free (pointer_name);
  • malloc() function in C
    • The malloc() function allocates single block for memory.
  • calloc() function in C
    • The calloc() function allocates multiple block for memory.
  • realloc() function in C
    • You can reallocate the memory by realloc() function.In other words it changes the memory size.
  • free() function in C
    • The memory occupied by malloc() or calloc() functions must be released by calling free() function.




More Differences