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 programming.

Let us get to know what is dynamic memory allocation in C. 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. Still have doubts, hire the C Programming assignment helper and clear your all doubts.

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

But is this possible? Yes, absolutely!

What is dynamic memory allocation in C Programming?

 

Let us find out what dynamic memory allocation in C is and how it can be used. Also, if you are aware about arrays in C programming then you can also learn about building a max heap using an array in C programming.

 

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 of Dynamic Memory Allocation in C using 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.

The 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 Dynamic Memory Allocation in C using 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 Dynamic Memory Allocation in C using 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. Also, if you are stuck in your C++ coding then you can always use our C++ homework help services and get your all doubts cleared by the best IT experts.

 

Output:

 

output for Dynamic Memory Allocation in C using 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. So, Polish your programming skills by learning about dynamic memory allocation in C. If you are interested in learning another topic about stack then read this article about implementation of stack using linked list in C programming.

Hire Top-rated Experts now

Leave a Comment

Your email address will not be published. Required fields are marked *