Difference Between Static and Dynamic Memory Allocation

Difference Between Static and Dynamic Memory Allocation in C

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 Chart

Static Memory AllocationDynamic 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 program.Memory can be Changed while executing program.
Used in an array.Used in a linked list.
It is fast and saves running time.It is a bit slow.
It allocates memory from stack.It allocates memory from heap.
Allocated memory stays from start to end of program.Memory can be allocated at any time and can be released at any time.
It is less efficient than a Dynamic allocation strategy.It is more efficient than a 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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here