The Blog

Dynamic Memory Allocation In C

Dynamic Memory Allocation In C

Do you know about Dynamic Memory Allocation? Today’s post will be about Dynamic Memory Allocation in C.

Let us get to know about what is dynamic memory allocation in C. So, let us begin this post with the question of what is dynamic memory allocation?

Let’s imagine a situation.

For instance, you are writing a C program to find the sum of some integers entered by the user. For storing those numbers, you declare an array of size 30.

Now, the memory for storing 30 integers is reserved.

But what if the user only wants to enter 10 integers?

In that case, all the remaining memory would go to waste. As programmers, we do not want to waste our resources.

So, what can you do?

The solution is to allocate the memory while the program is running.

In other words, you need to allocate the memory ‘dynamically’ to store the integers.

But is this possible? Yes, absolutely!

Dynamic memory allocation in C

Let us find out what dynamic memory allocation in C is and how it can be used.

 

What is Dynamic Memory Allocation in C?

 

To state it simply, dynamic memory allocation in C is the process of allocating or assigning memory to variables during the run time or execution of the program.

In the C programming language, we can facilitate the process of dynamic memory allocation using 4 library functions.

These 4 library functions are:

  • malloc()
  • calloc()
  • free()
  • realloc()

All these functions are defined under the header file <stdlib.h>

Let us examine what these functions are. Let’s also get to know how can we use the above 4 functions with the help of example codes.

 

Dynamic Memory Allocation in C using malloc()

 

The malloc() or ‘memory allocation’ function in C allocates a single memory block of a set size. This block initially contains some garbage value.

By default, it returns a pointer of the type void.

Syntax: p = (caste type)*malloc(size);

Let us see how we can allocate memory to ‘n’ integers using malloc()

The syntax: p = (int)*malloc(n*sizeof(int));

Below is an example to help you understand the malloc() function.

 

Example:

 

#include<stdio.h>

#include<stdlib.h>

int main()

{

    int *arr;

    int n, i;

    printf("\t\t\t Dynamic Memory Allocation using malloc() \n");

    printf("How many numbers do you want to enter? \n");

    scanf("%d", &n);

    // allocating memory for n integers

    arr = (int *)malloc(n * sizeof(int));

    if(arr == NULL){

    printf("Memory cannot be allocated!");

    }else{

            for(i=0; i<n; i++){

            printf("Enter element at arr[%d] \n", i);

            scanf("%d", (arr+i));

            }

            printf("\n Entered numbers are...\n");

            for(i=0; i<n; i++){

            printf("%d ",*(arr+i));

         }

    }

}

Let us have a look at the output of the above C program to get to know how the code works.

 

Output:

 

output for malloc

Let us now look at the second function for dynamic memory allocation.

Let us see what calloc() does.

 

Dynamic Memory Allocation in C using calloc()

 

Another way to facilitate dynamic memory allocation in C is by using calloc() or the ‘contiguous allocation’ function.

The calloc() function allocates multiple blocks of memory for storing variables and returns a pointer of type void which can be cast to the type the user wants.

The calloc() function also initializes the blocks to zero.

Hence, unlike malloc(), no garbage value is present in the memory blocks.

Syntax for storing ‘n’ number of elements/values:  p = (caste type)*calloc(n, size);

Let’s see an example program to know how can we use calloc() for allocating the memory dynamically.

 

Example:

 

#include<stdio.h>

#include<stdlib.h>

int main()

{

    int *arr;

    int n, i;

    printf("\t\t\t Dynamic Memory Allocation using calloc() \n");

    printf("\n How many numbers do you want to enter? \n");

    scanf("%d", &n);

    // allocating memory for n integers

    arr = (int *)calloc(n, sizeof(int));

    if(arr == NULL){

    printf("Memory cannot be allocated!");

    }else{

            for(i=0; i<n; i++){

                 printf("Enter element at arr[%d] \n", i);

                 scanf("%d", (arr+i));

            }

        }

        printf("\n Entered numbers are...\n");

            for(i=0; i<n; i++){

            printf("%d ",*(arr+i));

         }

    return 0;

}

The above program for dynamic memory allocation results in the output given below.

 

Output:

 

output for calloc

It is now time to examine the free() function.

Want to know how to use free()? Let’s continue!

 

Dynamic Memory Allocation in C using free()

 

The free() function does the opposite of malloc() and calloc(). What does that mean?

Well, unlike the malloc() or calloc() function, free() actually ‘de-allocates’ the previously allocated memory.

This means that the function helps in freeing and reducing memory wastage. This memory can be used later in the program.

Syntax: free(p);

Here, ‘p’ is the variable that was previously allocated to the memory.

An example code is given below.

 

Example:

 

#include<stdio.h>

#include<stdlib.h>

int main()

{

    int *arr;

    int n, i;

    printf("\t\t\t Dynamic Memory Allocation - De-allocation using free() \n");

    printf("\n How many numbers do you want to enter? \n");

    scanf("%d", &n);

    // allocating memory for N integers

    arr = (int *)calloc(n, sizeof(int));

    if(arr == NULL){

    printf("Memory cannot be allocated!");

    }else{

            for(i=0; i<n; i++){

                 printf("Enter element at arr[%d] \n", i);

                 scanf("%d", (arr+i));

            }

            printf("\n Entered numbers are...\n");

            for(i=0; i<n; i++){

            printf("%d ",*(arr+i));

         }

        }

         //free memory

         free(arr);

         printf("\n\nMemory Freed!");

}

Now, let us have a look at the output for the C program we just went through.

 

Output:

 

output for free

Let us now move on to the last function which we need to discuss.

Want to know what realloc() function does? Keep reading…

 

Dynamic Memory Allocation in C using realloc()

 

We use the realloc() function in C to ‘re-allocate’ or re-size the memory block which was previously allocated by using the malloc() or calloc() functions.

The memory block which was already allocated to the variables does not get altered while new blocks get initialized with garbage values.

Syntax: p = realloc(p, Newsize);

Have a look at the example code given below.

 

Example:

 

#include<stdio.h>

#include<stdlib.h>

int main()

{

    int *arr;

    int n, i, add;

    printf("\t\t\t Dynamic Memory Allocation using realloc() \n");

    printf("\n How many numbers do you want to enter? \n");

    scanf("%d", &n);

    // allocating memory for N integers

    arr = (int *)calloc(n, sizeof(int));

    if(arr == NULL){

    printf("Memory cannot be allocated!");

    }else{

            for(i=0; i<n; i++){

                 printf("Enter element at arr[%d] \n", i);

                 scanf("%d", (arr+i));

            }

            printf("\n Entered numbers are...\n");

            for(i=0; i<n; i++){

            printf("%d ",*(arr+i));

         }

        }

        printf("\n How many more numbers do you want to add? \n");

        scanf("%d", &add);

        // reallocation of memory

        arr = realloc(arr, (n*sizeof(int)+add));

        for(i=n; i<n+add; i++){

             printf("Enter element: \n");

             scanf("%d", (arr+i));

        }

printf("\n Entered numbers are...\n");

            for(i=0; i<n+add; i++){

            printf("%d ",*(arr+i));

         }
}

Do you want to have a look at the output of this C program? Have a look below and see how the code works.

 

Output:

 

output for realloc

 

Dynamic memory allocation is an important process every programmer should know about.

It is also extremely useful when you are working with data structures.

Polish your programming skills by learning about dynamic memory allocation in C.

If you need help with your C programming homework don’t worry! Visit https://codingzap.com/ and our expert team will be there to help you out.

We also offer a wide range of programming and coding help services for you to benefit from. Don’t miss out!

Check out our other listed services as well!

Computer science Homework Help

Java Homework Help 

C++ Programming Homework Help

Python Homework Help

PHP Homework Help

Sanjana Grover
Sanjana Grover

Leave a Comment