Dynamic memory allocation in C

Dynamic memory allocation enables programmers to allocate memory during program runtime. For example if we declare an array of size 50, then we can not change its capacity during runtime. But we can do it by some function related to dynamic memory allocation.

In this article we will learn about dynamic memory allocation in C programming. There are 4 functions to enable us allocate memory dynamically in stdlib.h header file. We will learn them to use in our program here.

  • malloc() — use to allocate single block of memory
  • calloc() — use to allocate multiple block of memory
  • realloc() — reallocate memory of malloc() and calloc()
  • free() — use to free allocated memory

We will use this 4 function to learn dynamic memory allocation in this guide.

Using malloc() function in C language

malloc() is a library function which is used to dynamic memory allocation. It allocates block of memory of the specified number of bytes. malloc() returns a void pointer which should be casted in pointers of any form. malloc() returns NULL pointer if the memory is not sufficient. Here is the syntax of malloc() function.

// syntax of malloc() function

ptr = (cast_type*) malloc(size_in_byte);

See the given C program to understand the use of malloc() function. Here we will allocate memory dynamically for the number of students given by the user.

// using malloc() function in C

#include <stdio.h>
#include <stdlib.h>
int main(){
    float *ptr, sum = 0;
    int num, c;

    printf("Enter the number of students here : ");
    scanf("%d", &num);

    ptr = (float*)malloc(num * sizeof(float));

    if(ptr == NULL){
        printf("Memory allocation is not successful.\n");
        exit(1);
    }

    for(c = 0; c < num; c++){
        printf("Enter marks of student %d here : ", c+1);
        scanf("%f", ptr + c);
    }

    for(c = 0; c < num; c++){
        sum += *(ptr+c);
    }

    printf("\nAverage marks of all students is = %.2f\n", sum/num);

    return 0;
}

Output of the program will be as follows:

dynamic-memory-allocation-in-c-malloc-function-in-c

Using calloc() function with example program

calloc() is also used for dynamic memory allocation and this is another function used to allocate memory dynamically in C. It takes two parameters to work. First parameter is the number of element and second is the size of element for which we want to allocate the memory. calloc() also returns NULL if memory is not sufficient.

If we want to allocate memory for 4 float type data then the first parameter will be 4 which is the number of element and the second parameter will be the size of float variable which is 4.

Syntax of calloc() function in C :

// syntax of calloc() function in C 

ptr = (cast-type*)calloc(number_of_var, size_in_bytes);  

Now, let’s see the following C program to learn about calloc() function in C. Here we will allocate memory dynamically for an array of given size by the user.

// using calloc() function in C

#include<stdio.h>
#include<stdlib.h>
int main(){
  int *ptr, c, num;

  printf("Enter size of array here : ");
  scanf("%d", &num);

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

  if(ptr == NULL){
    printf("Memory is not successfully allocated.\n");
    exit(1);
  }

  for(c = 0; c < num; c++){
    printf("Enter value of index %d here : ", c);
    scanf("%d", ptr + c);
  }
  printf("\nYour given array of size %d is ......\n\n", num);

  for(c = 0; c < num; c++){
    printf("%d ", *(ptr + c));
  }
  return 0;
}

Compile and run the program. Then you will get the output like this.

dynamic-memory-allocation-in-c-calloc-function-in-c-c-realloc-c-free-function

realloc() function in C & its use

If we allocate memory using malloc() or calloc() function but the memory is not sufficient for store our data now, then we can reallocate using realloc() function. The realloc() function changes the size of memory for predefined memory size using calloc() or malloc().

The syntax of realloc() function is given bellow :

// syntax of realloc() function in C

ptr = realloc(ptr, new-size_in_byte);  

Here, we will see a C program using realloc() function to reallocate the size of memory. Let’s see this program bellow;

// use of realloc() function in C

#include<stdio.h>
#include<stdlib.h>
int main(){
  int j, num, *ptr, init_size, new_size;

  printf("Enter the size of array here : ");
  scanf("%d", &init_size);
  ptr = (int*)calloc(init_size, sizeof(int));

  if(ptr == NULL){
    printf("Memory is not allocated successfully.\n");
    exit(1);
  }

  for(j = 0; j < init_size; j++){
    printf("Enter element of index %d : ", j);
    scanf("%d", ptr + j);
  }

  printf("\nInitial array is....... \n");

  for(j = 0; j < init_size; j++){
    printf("%d ", *(ptr + j));
  }

  printf("\n\nEnter how many block of array you want to increase : ");

  scanf("%d", &new_size);
  ptr = (int*)realloc(ptr, (init_size + new_size) * sizeof(int));

  if(ptr == NULL){
    printf("Memory is not allocated successfully.\n");
    exit(1);
  }

  printf("\nEnter more %d integers here\n", new_size);

  for(j = init_size; j < (init_size + new_size); j++){
    printf("Enter element at index %d: ", j);
    scanf("%d", ptr + j);
  }

  printf("\nFinal array array after increasing is....... \n");

  for(j = 0; j < (init_size + new_size); j++){
    printf("%d ", *(ptr + j));
  }
  return 0;
}

Output of this program will be as follows;

Enter the size of array here : 5
Enter element of index 0 : 1
Enter element of index 1 : 2
Enter element of index 2 : 3
Enter element of index 3 : 4
Enter element of index 4 : 5

Initial array is.......
1 2 3 4 5

Enter how many block of array you want to increase : 6

Enter more 6 integers here
Enter element at index 5: 6
Enter element at index 6: 7
Enter element at index 7: 8
Enter element at index 8: 9
Enter element at index 9: 10
Enter element at index 10: 11

Final array array after increasing is.......
1 2 3 4 5 6 7 8 9 10 11

free() function in C, free up memory

If our allocated memory by malloc() or calloc() is not necessary now or if we need to free some of our allocated memory then we have to use free() function. free() function allows the best utilization of out memory as we can free our allocated memory by this.

Now, let’s see the syntax of free() function :

// syntax of free() function

free(ptr);

We can use free() function with both malloc() and calloc(). Here we will see both the use of free() function with calloc() and malloc().

using free() function with malloc()

See the following program where we have used the free function with malloc(). We have used malloc() for dynamic memory allocation and then used free() function to free up space. Here we will add all the integers given by the user and the use free() function.

// free() function with malloc() in C

#include <stdio.h>
#include <stdlib.h>
int main(){
  int c, num, *ptr, sum = 0;

  printf("Enter number of elements here : ");
  scanf("%d", &num);

  ptr = (int*) malloc(num * sizeof(int));

  if(ptr == NULL){
    printf("Memory allocation failed.\n");
    exit(1);
  }

  printf("Enter %d elements : ", num);
  for(c = 0; c < num; ++c) {
    scanf("%d", ptr + c);
    sum += *(ptr + c);
  }

  printf("\nSum of all elements is = %d\n", sum);

  free(ptr);
  return 0;
}

Output of program

Enter number of elements here : 8
Enter 8 elements : 1 2 3 4 5 6 7 8

Sum of all elements is = 36

using free() function with calloc()

Here in this program we will see the use of free() function with calloc() function in C programming. Let’s see the program bellow where we have used calloc() function for dynamic memory allocation and free() function to free up space in the memory;

// free() function with calloc() in C

#include <stdio.h>
#include <stdlib.h>
int main(){
  int k, num, *ptr, sum = 0;
  printf("Enter number of elements here : ");
  scanf("%d", &num);

  ptr = (int*) calloc(num, sizeof(int));
  if(ptr == NULL) {
    printf("Memory is not allocated successfully.\n");
    exit(1);
  }

  printf("Enter %d elements here : ", num);
  for(k = 0; k < num; ++k){
    scanf("%d", ptr + k);
    sum += *(ptr + k);
  }

  printf("\nSum of given integers is = %d\n", sum);

  free(ptr);
  return 0;
}

Compile and run the program to get following output.

Enter number of elements here : 5
Enter 5 elements here : 10 20 30 40 50

Sum of given integers is = 150

Previous pagePointer to function in C

Next pageFile input output in C