Dynamic Memory Allocation in C Using Malloc(), Calloc(), Free(), Realloc()


Dynamic memory allocation in C



















To understand the concept of dynamic memory allocation in C, first, we need to understand why we need it? Whether we talk about the C programming language or some other programming language, there are some rules for every programming language. C is a structured programming language and it has some fixed rules. Let's try to understand that need and concept of dynamic memory allocation in C with the help of array.



Declaration of an array in C

int employees [100];

An int is of 4 bytes, 100*4 = 400 bytes are reserved in memory. If you want to store details of 70 employees, you can do it but 30 memory locations will be wasted and if you want to store details of 120 employees, you can store the detail of 100 employees, but details of 20 employees are not saved. Are you thinking that why this is happening? This is happening because we have used the concept of static memory here if we want that memory should be allocated at the time of execution of the program. So, Dynamic memory allocation concept meets our needs. Let's try to understand this concept. 

What is Dynamic Memory Allocation in C?

Dynamic memory allocation in C helps us to allocate memory during runtime of the program. The dynamic memory allocation is done by using the standard library function <stdlib.h>. This library function consist of malloc (), calloc(), free() and realloc() function in C.



1. malloc ( )

"malloc" or memory function allocates a block of memory of specified size. It returns a void pointer which can be used in a pointer of any form. 

Syntax
pointer_variable = (cast-type*)malloc(Size_in_bytes);

For example
pointer_variable = (int*)malloc(30*sizeof(int));


We know that the size of the integer data types in C is of 4 bytes, the above statement allocates 120 bytes of memory and pointer_variable holds the address of the first byte of the memory block. 

Dynamic memory allocation in c












If 40 bytes are not available in memory that means insufficient space then memory allocation fails and it returns a null pointer

Dynamic memory allocation in C using malloc ( ) function
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *pointer; // This pointer will hold the address of first byte of allocated block of memory.
    int num, i, total = 0;
    //Number of elements in an array.
    num = 4;
    printf ("Enter number of elements in an array:%d\n",num);
    //Allocate memory using malloc () function
    pointer = (int*)malloc(num*sizeof(int));
    //Check memory is successfully allocated by malloc () function
    if(pointer == NULL)
    {
        printf("Memory not allocated\n");
    }
    else
    {
        printf("Memory is allocated using malloc function\n");
        //Elements of an array
        for (i=0;i<num;i++)
        {
            pointer[i]=i+1;
        }
        printf("Elements of an array\n");
        for(i=0;i<num;i++)
        {
            printf("%d\n",pointer[i]);
        }
    }
    return 0;
}

Output
Enter the number of elements in an array:4
Memory is allocated using malloc function
Elements of an array
1
2
3
4

2. calloc ( )

"calloc" or contiguous allocation is used to allocate the block of memory during runtime of the program of the specified size. Every block of memory is initialized with default value zero.

Syntax
pointer_variable = (cast-type*)calloc(number_of_elements, Size_in_bytes);

For example
pointer_variable=(int*) calloc(10, sizeof(int));

The above statement contiguously allocates 40 bytes of memory for 10 elements and each element is of 4 bytes.

Dynamic memory allocation in C












Dynamic memory allocation in C using calloc ( ) function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *pointer; //This pointer will hold the address of first byte of allocated block of memory.
    int num, i, total = 0;
    num = 4; //Number of elements in an array
    //Dynamic memory allocation in C using calloc function
    pointer = (int*)calloc(num,sizeof(int));
    if (pointer==NULL)
    {
        printf("Memory space is insufficient\n");
    }
    else
    {
        printf("Memory is allocated\n");
        for(i=0;i<num;i++)
        {
            pointer[i]=i+2;
        }
        //An array elements
        for(i=0;i<num;i++)
        {
            printf("%d\n",pointer[i]);
        }
    }
    return 0;
}


Output
Memory is allocated
2
3
4
5

3. free ( )

This function is used to de-allocate memory. Calloc ( ) and malloc ( ) function does not de-allocate memory by themselves. So, the free ( ) function is used, it reduces the wastage of memory.

Syntax
free (pointer);

Dynamic memory allocation in C





















Free allocated memory using the free ( ) function.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *pointer; //This pointer will hold the address of first byte of allocated block of memory.
    int num, i, total = 0;
    num = 4; //Number of elements in an array
    //Dynamic memory allocation in C using calloc function
    pointer = (int*)calloc(num,sizeof(int));
    if (pointer==NULL)
    {
        printf("Memory space is insufficient\n");
    }
    else
    {
        printf("Memory is allocated\n");
    }
    free(pointer);
    printf("Memory is freed");
    return 0;
}


Output
Memory is allocated
Memory is freed

4. realloc ( ) 

"realloc" or re-allocation function is used to change the allocated memory. If the memory allocated by calloc and malloc function is insufficient then the realloc function is used to re-allocate memory dynamically.

Syntax
pointer_variable= realloc(pointer_variable, new_size);

Dynamic memory allocation in C





















Re-allocate memory using realloc () function
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *pointer; //This pointer will hold the address of first byte of allocated block of memory.
    int num, i, total = 0;
    num = 4; //Number of elements in an array
    //Dynamic memory allocation in C using calloc function
    pointer = (int*)calloc(num,sizeof(int));
    if (pointer==NULL)
    {
        printf("Memory space is insufficient\n");
    }
    else
    {
        printf("Memory is allocated\n");
        for(i=0;i<num;i++)
        {
            pointer[i]=i+2;
        }
        //An array elements
        for(i=0;i<num;i++)
        {
            printf("%d\n",pointer[i]);
        }
    }
    //Change the size of new array
    int new_num=10;
    //Re-allocate memory using realloc() function
    pointer=realloc(pointer,new_num*sizeof(int));
    for(i=5;i<new_num;++i)
    {
        pointer[i]=i+2;
    }
    //Print the elements of the array
    for(i=0;i<new_num;++i)
    {
        printf("%d\n",pointer[i]);
    }
    free(pointer);
    return 0;
}


Output
Elements in an array
2
3
4
5
New Elements in an array
2
3
4
5
5
6
7
8
9
10

Difference between static memory allocation and dynamic memory allocation in C

1. In static memory allocation, memory is allocated at compiling time and dynamic memory is allocated at executing time of the program.
2. In static memory allocation, memory size can't be changed during execution of the program, it's size is fixed but in dynamic memory allocation, size of memory can be changed during execution of the program.

Difference between malloc ( ) and calloc ( ) funtion in C


Dynamic memory allocation in C





















































Dynamic Memory Allocation in C Using Malloc(), Calloc(), Free(), Realloc() Dynamic Memory Allocation in C Using Malloc(), Calloc(), Free(), Realloc() Reviewed by Glory on 10:21 Rating: 5

No comments:

Powered by Blogger.