Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
malloc()
3.
calloc()
4.
realloc()
5.
free()
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

Dynamic Memory Allocation in C

Author Yashesvinee V
1 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

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. 

Also See, Sum of Digits in C and C Static Function.

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

 

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;
}

 

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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

 

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;
}

 

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

 

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;
}

 

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


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;
}


Also see, Short int in C Programming

FAQs

  1. 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.
     
  2. 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.

Key Takeaways

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

Previous article
How to deallocate memory without using free method in C Language?
Next article
How does the free() method know the size of memory to be de-allocated?
Live masterclass