Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Dynamic Memory Allocation?
3.
malloc()
4.
calloc()
5.
realloc()
6.
free()
7.
Frequently Asked Questions
7.1.
What is the difference between calloc and malloc?
7.2.
What is a pointer variable?
7.3.
What is the difference between dynamic and static memory allocation?
8.
Conclusion
Last Updated: Aug 3, 2024

Dynamic Memory Allocation in C

Author Yashesvinee V
1 upvote

Introduction

Memory allocations involve services that are executed to reserve space in the virtual memory of a computer. Dynamic memory allocation does this during runtime or program execution. It is extremely helpful when we want to create Data Structures without any upper limit or do not know the exact number of elements we will store in it. Dynamic memory allocation provides methods like malloc(), calloc(), realloc() and free() to allocate memory spaces that can be modified according to the programmer's needs during runtime. 

Dynamic Memory Allocation in C

Also See, Sum of Digits in C

What is Dynamic Memory Allocation?

Dynamic memory allocation allows allocation and deallocation of memory during runtime using functions like malloc(), calloc(), realloc(), and free(). It provides flexibility to manage memory for data structures whose size can change during program execution. This approach helps optimize memory usage, especially when dealing with large or variable-sized data.

malloc()

The word malloc refers to memory allocation. This function reserves a single block of memory of the specified number of bytes. It returns a pointer of void type that can be cast into any form. Since it is not initialised during allocation, it is filled with some garbage value until initialisation.

Syntax:

ptr = (castType*) malloc(size);
// ptr is a pointer variable
You can also try this code with Online C Compiler
Run Code

 

Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
  int n = 4;
  int i, *ptr, sum = 0;

  ptr = (int*) malloc(n * sizeof(int));
 
  // if memory is not allocated
  if(ptr == NULL) {
    printf("Memory not allocated.");
    exit(0);
  }

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

  printf("Sum = %d", sum);
  
  return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output:

Enter elements: 
3
5
7
9
Sum = 24

 

The above example shows the use of malloc function to perform dynamic memory allocation and store an array of 4 integers.

calloc()

The name calloc refers to contiguous allocation. This function allocates n blocks of memory dynamically to store n values and initialises all bits to zero. 

Syntax:

ptr = (castType*)calloc(n, size);
// ptr is a pointer variable
You can also try this code with Online C Compiler
Run Code

 

Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
  int n = 4;
  int i, *ptr, sum = 0;
 
  ptr = (int*) calloc(n, sizeof(int));
  
  if(ptr == NULL) {
    printf("Memory not allocated.");
    exit(0);
  }

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

  printf("Sum = %d", sum);
  
  return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output:

Enter elements: 
4
5
6
7
Sum = 22

 

The above example shows the use of calloc function to allocate memory dynamically and store an array of 4 integers.

realloc()

The realloc() method is used when the present allocated memory is not sufficient. It resizes an existing allocated memory block. It first deallocates the old object and reallocates it with the newly specified size. If the new size is lesser than the old size, the contents of the newly allocated memory will be the same as before. However, if the bytes in the newly created object goes beyond the old size, the values of the object will be indeterminate.

Syntax:

ptr = realloc(ptr, n*sizeof(data_type);
// ptr is a pointer variable
You can also try this code with Online C Compiler
Run Code

 

Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
  int *ptr, i , n = 4, m = 6;
  
  ptr = (int*) malloc(n * sizeof(int));

  printf("Addresses of memory to hold 4 integers:\n");
  for(i = 0; i < n; ++i)
    printf("%pc\n",ptr + i);

  printf("\nResizing allocated memory to hold 6 integers... ");
  
  // re-allocation 
  ptr = realloc(ptr, m * sizeof(int));

  printf("Addresses of newly allocated memory:\n");
  for(i = 0; i < m; ++i)
    printf("%pc\n", ptr + i);
  
  return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output:

Addresses of memory to hold 4 integers:
0x7efc01150560c
0x7efc01150564c
0x7efc01150568c
0x7efc0115056cc

Resizing allocated memory to hold 6 integers... 
Addresses of newly allocated memory:
0x7efc01150560c
0x7efc01150564c
0x7efc01150568c
0x7efc0115056cc
0x7efc01150570c
0x7efc01150574c

You can also read about the dynamic arrays in c, and  Tribonacci Series

free()

The free() method is used to dynamically deallocate the memory. It helps avoid wastage of memory space by freeing unused/unwanted memory resources.

Syntax:

free(ptr);
//ptr is a pointer to the memory block that is to be freed
You can also try this code with Online C Compiler
Run Code


Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
  int n = 4;
  int i, *ptr, sum = 0;
 
  ptr = (int*) calloc(n, sizeof(int));
  
  if(ptr == NULL) {
    printf("Memory not allocated.");
    exit(0);
  }
   
  free(ptr);
  return 0;
}
You can also try this code with Online C Compiler
Run Code


Also see, Short int in C Programming

Frequently Asked Questions

What is the difference between calloc and malloc?

A malloc and calloc are functions used for memory allocation and management. The memory allocated by calloc is initialised with 0, while malloc does not initialise the allocated memory. The malloc function takes one argument, but calloc takes two.

What is a pointer variable?

A pointer is a variable that contains the address of another variable in the memory. It points to a data type (like int ) of the same type and is created with the * operator. The size of a pointer variable depends on the compiler.

What is the difference between dynamic and static memory allocation?

Static memory allocation allows fixed memory size after allocation while Dynamic memory allocation allows changes in the memory size after allocation.

Conclusion

This article extensively discusses Dynamic memory allocation in C. We hope that this blog has helped you enhance your knowledge about the different ways of allocating memory dynamically in C. If you would like to learn more, check out our articles on the Coding Ninjas Library. Do upvote our blog to help other ninjas grow. Happy Coding!

Related Links:

Dynamic Memory

Ternary Operator in C

Difference between static and dynamic memory allocation

Live masterclass