Table of contents
1.
Introduction
2.
What is Static Memory allocation?
2.1.
Properties of Static Memory allocation
2.2.
Advantages of Static Memory allocation
2.3.
Disadvantages of Static Memory allocation
3.
What is Dynamic Memory allocation?
3.1.
Properties of Dynamic Memory allocation
3.1.1.
malloc()
3.1.2.
calloc()
3.1.3.
realloc()
3.1.4.
free()
3.2.
C program for Dynamic Memory allocation
3.3.
Advantages of Dynamic Memory allocation
3.4.
Disadvantages of Dynamic Memory allocation
4.
Difference Between Static and Dynamic Memory Allocation
5.
Frequently Asked Questions
5.1.
What is dynamic memory allocation in OS?
5.2.
What is the difference between static and heap memory allocation?
5.3.
What is the difference between malloc and calloc?
6.
Conclusion
Last Updated: Dec 18, 2024
Easy

Difference between Static and Dynamic Memory Allocation in C

Author Shivam Verma
3 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Memory allocation refers to assigning a particular space in a computer's memory for a computer program or code.

There are two types of memory allocations. 

  1. Static Memory allocation
  2. Dynamic Memory allocation 
static memory allocation

The key difference between Static and Dynamic memory allocation is that Static memory allocation allows fixed memory size after allocation while Dynamic memory allocation allows changes in the memory size after allocation

What is Static Memory allocation?

Static memory allocation is also known as Compile-time memory allocation because the memory is allocated during compile time. In this type of memory allocation, the memory that the program can use is fixed i.e. we can not allocate or deallocate memory during the program's execution. In many applications, it is not possible to predict how much memory will be needed by the program at run time.

Properties of Static Memory allocation

  1. Memory allocation is done during compile time.
  2. Stack Memory is used here.
  3. Memory cannot be changed while executing a program.
  4. The static memory allocation is fast and saves running time.
  5. It is less efficient as compared to Dynamic memory allocation.
  6. The allocation process is simple.

Advantages of Static Memory allocation

  1. The memory is allocated during compile time.
  2. It is easy to use.
  3. It uses a stack Data Structure.
  4. The execution time is efficiently controlled.

Disadvantages of Static Memory allocation

  1. This allocation method leads to memory wastage.
  2. Memory cannot be changed while executing a program.
  3. Exact memory requirements must be known.
  4. If memory is not required, it cannot be freed.

What is Dynamic Memory allocation?

Dynamic memory allocation is also known as Runtime memory allocation because the memory is allocated during runtime or program execution. The allocation and release of the memory space can be done using the library functions of stdlib.h header file. These functions allocate memory from a memory area called heap and deallocate this memory whenever not required so that it can be used for some other purpose.

Properties of Dynamic Memory allocation

  1. Memory is allocated at runtime.
  2. Memory can be allocated and released at any time.
  3. Heap memory is used here.
  4. Dynamic memory allocation is slow.
  5. It is more efficient as compared to Static memory allocation
  6. The allocation process is simple is complicated.
  7. Memory can be resized dynamically or reused.
     

The library functions of the stdlib.h header file, which helps to allocate memory dynamically are.  

  1. malloc()
  2. calloc()
  3. realloc()
  4. free()

malloc()

This function is used to allocate the single block of requested memory. On Success, the malloc() function returns a pointer to the first byte of the allocated memory. The malloc() function gives a NULL output when the memory is not enough.

Syntax: 

ptr=(data_type *)malloc(specified_size)

Here in the above syntax, ptr is a pointer of type data_type, and specified_size is the size in bytes required to allocate. The cast (data_type *) typecast the pointer returned by the malloc() function.

Example 

ptr = (int*)malloc(100);

In the above example, the statement allocates 100 bytes of memory space, and the pointer variable ptr stores the address of the first byte in the memory.

calloc()

The calloc() function is used to allocate the memory as a number of elements of a given size. The calloc() function is similar to malloc() function. The only difference is that it takes two argument values. The first argument specifies the number of data items for which space is required, and the second argument specifies the size of each data item.

Syntax: 

ptr=(data_type *)calloc(n, specified_size)

Here in the above syntax, ptr is a pointer of type data_type, n is the number of data items,  and specified_size is the size in bytes required to allocate. The cast (data_type *) typecast the pointer returned by the malloc() function.

Example 

ptr = (int*)calloc(4, sizeof (int));

In the above example, the statement allocates four blocks of memory, each block contains 4 bytes, and the starting address is stored in the pointer variable ptr.

realloc()

The realloc() function is used to increase the memory allocated by malloc() or calloc() function. This function alters the size of the memory block without losing the old data. The realloc() function takes two argument values. The first argument is a pointer variable to the block of memory that was previously allocated by calloc() or malloc(), and the second argument is the new size for that memory block. 

Syntax: 

realloc(pointer_variable, n);

Here in the above syntax, pointer_variable is a pointer to the block of memory that was previously allocated by malloc() or calloc() function, and n is the new size for that memory block.

Example 

int *ptr;
ptr = (int*)malloc(100);
ptr = (int*)realloc(ptr, 400);

Here in the above example, we increased memory size from 100 bytes to 400 bytes.

free()

When memory is allocated dynamically by the malloc() and calloc() function, it should always be released when it is no longer required. Otherwise, it will consume memory until the program exit. The free() function is used to release this allocated memory space.

Syntax:

free(pointer_variable);

Here in the above syntax, the memory block pointed by the pointer 'pointer_variable' would be released back to the system.

C program for Dynamic Memory allocation

Here is a C program to illustrate the Dynamic Memory Allocation.

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int *ptr1, *ptr2;
    int size=10;
    printf("The size of given array is: %d\n", size);
    ptr1=(int*)malloc(size*sizeof(int));
    ptr2=(int*)calloc(size,sizeof(int));
    ptr1=(int*)realloc(ptr1, 20);
    if (ptr1==NULL || ptr2==NULL)
    {
        printf("Memory allocation not sucessful.\n");
        exit(0);
    }
    else
    {
        printf("Memory allocation using malloc() and calloc() is successful.\n");
        ptr1=(int*)realloc(ptr1, 20);
        if (ptr1==NULL)
        {
            printf("Memory allocation not sucessful.\n");
            exit(0);
        }
        else
        {
            printf("Memory reallocation using realloc() is successful.\n");
        }
    }
    free(ptr1);
    printf("Memory became free.\n");
    free(ptr2);
    printf("Memory became free.\n");
    return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

The size of given array is: 10
Memory allocation using malloc() and calloc() is successful.
Memory reallocation using realloc() is successful.
Memory became free.
Memory became free.

Here we see how malloc(), calloc, realloc(), and free() functions work in a program.

Try to implement on an online compiler for better practice.

Advantages of Dynamic Memory allocation

  1. This allocation method has no memory wastage.
  2. The memory allocation is done at run time.
  3. Memory size can be changed based on the requirements of the dynamic memory allocation.
  4. If memory is not required, it can be freed.

Disadvantages of Dynamic Memory allocation

  1. It requires more execution time due to execution during runtime.
  2. The compiler does not help with allocation and deallocation. Programmer needs to both allocate and deallocate the memory.

Difference Between Static and Dynamic Memory Allocation

Let us note down the points of differences between static and dynamic memory allocation in C as follows:

ParametersStatic Memory AllocationDynamic Memory Allocation
Memory AssignmentDone at compile time.Done at runtime using functions like malloc(), calloc(), etc.
Memory SizeFixed and predefined during program design.Flexible and can be changed during program execution.
EfficiencyFaster because memory is allocated at compile time.Slower as memory allocation happens at runtime.
Memory ManagementManaged by the compiler automatically.Managed manually by the programmer.
FlexibilityLess flexible as size cannot change during runtime.Highly flexible, allowing dynamic resizing.
Functions UsedVariables and arrays are examples of static allocation.Functions like malloc(), calloc(), realloc(), and free() are used.
UsageUseful for scenarios with known, fixed memory needs.Suitable for scenarios with uncertain or variable memory needs.
Memory ReleaseAutomatically released when the program exits.Must be explicitly freed by the programmer using free().

Check this out, Difference Between Rank and Dense Rank

Frequently Asked Questions

What is dynamic memory allocation in OS?

Dynamic memory allocation in an operating system refers to the process of allocating memory at runtime for processes and programs. It involves managing memory segments efficiently, ensuring proper allocation and deallocation to prevent memory leaks and optimize system performance. 

What is the difference between static and heap memory allocation?

Static memory allocation assigns memory addresses to variables during compile time, while heap memory allocation dynamically assigns memory addresses during runtime using functions like malloc() and calloc(). Static allocation's memory size is fixed, determined by the compiler, whereas heap allocation's size can vary based on program needs. 

What is the difference between malloc and calloc?

  • malloc(): Allocates a single block of memory without initializing it.
  • calloc(): Allocates multiple blocks of memory and initializes all bytes to zero.
     

Both are used for dynamic memory allocation but differ in initialization and block allocation.

Conclusion

In this article, we have extensively discussed Static and Dynamic Memory allocation and see the Dynamic Memory allocation in your C program using standard library functions like malloc(), calloc(), free(), and realloc(). We hope that this blog has helped you enhance your knowledge, and if you wish to learn more, check out our article on Dynamic memory and visit our library of curated blogs by clicking here. Do upvote our blog to help other ninjas grow. Happy Coding!

Recommended reading: 

Clean Architecture
Demand Paging in OS

Live masterclass