Table of contents
1.
Introduction
2.
What is Dynamic Memory Allocation in C?
3.
malloc()
3.1.
Syntax
3.2.
Example
4.
calloc()
4.1.
Syntax
4.2.
Example
5.
realloc()
5.1.
Syntax
5.2.
Example
6.
free()
6.1.
Syntax
6.2.
Example
7.
Difference between Static Memory Allocation and Dynamic Memory Allocation
8.
Importance of Dynamic Memory Allocation
8.1.
Key Points:
9.
Issues Related to Dynamic Memory Allocation
9.1.
Common Issues:
10.
Advantages of Dynamic Memory Allocation
11.
Disadvantages of Dynamic Memory Allocation
12.
Frequently Asked Questions
12.1.
What is the use of malloc in C?
12.2.
What is the difference between calloc and malloc?
12.3.
What is a pointer variable?
12.4.
What is the difference between dynamic and static memory allocation?
13.
Conclusion
Last Updated: Mar 31, 2025
Medium

Dynamic Memory Allocation in C

Author Yashesvinee V
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Memory allocations involve services that are executed to reserve space in the virtual memory of a computer. Dynamic memory allocation in C is done 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

What is Dynamic Memory Allocation in C?

Dynamic memory allocation in C 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.

  1. malloc()
     
  2. calloc()
     
  3. realloc()
     
  4. free()

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

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

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

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

Difference between Static Memory Allocation and Dynamic Memory Allocation

ParametersStatic Memory AllocationDynamic Memory Allocation
Memory Allocation TimeMemory is allocated at compile time.Memory is allocated at runtime.
Memory SizeFixed size determined during compile time.Size can be changed during program execution.
FlexibilityLess flexible, memory size cannot be changed.More flexible, memory size can be adjusted dynamically.
Memory DeallocationNo manual deallocation; memory is released after program ends.Memory must be manually deallocated using free().
Memory ManagementManaged by the compiler.Managed by the programmer.
Exampleint arr[10];int* arr = (int*)malloc(10 * sizeof(int));
EfficiencyFaster due to compile-time allocation.Slower due to runtime allocation and management.

Importance of Dynamic Memory Allocation

Dynamic Memory Allocation is vital in managing memory effectively during program execution. Unlike static memory allocation, it offers flexibility and optimizes memory usage, especially for applications where data size varies.

Key Points:

  • Memory Efficiency: Allocates memory only when needed, preventing unused memory from being wasted.
     
  • Adaptability: Allows handling data structures whose size cannot be determined in advance, making it suitable for variable data requirements.
     
  • Optimal Performance: Reduces memory overhead by allocating memory on demand and deallocating it when no longer needed.
     
  • Supports Scalability: Essential for applications like databases, games, and large software systems that require scalable memory management.

Issues Related to Dynamic Memory Allocation

Despite its advantages, dynamic memory allocation poses several challenges that need careful handling to avoid errors and inefficiencies.

Common Issues:

  • Increased Complexity: Managing memory allocation manually, especially in large programs, requires extra effort to avoid errors like memory leaks and fragmentation.
     
  • Accessing Freed Memory (Dangling Pointers): If memory is freed but still accessed later, it causes unpredictable behavior or crashes in the program.
     
  • Performance Overhead: The runtime management of dynamic memory incurs additional processing time, which can affect the overall speed of the program.

Advantages of Dynamic Memory Allocation

  • Flexible Memory Management: Memory can be allocated or deallocated as needed during program execution.
  • Efficient Use of Memory: It allows the program to request memory based on the actual data size, saving memory.
  • Handling Large Data: Enables handling large amounts of data that cannot be determined at compile time.
  • Memory Allocation at Runtime: Useful for creating data structures (like linked lists, trees) where the size is not known beforehand.
  • Supports Complex Data Structures: Allows creation of more complex data structures such as dynamic arrays and lists.

Disadvantages of Dynamic Memory Allocation

  • Memory Leaks: If memory is not properly deallocated using free(), it leads to memory leaks, causing resource wastage.
  • Fragmentation: Over time, dynamic memory allocation can cause memory fragmentation, making it harder to allocate large contiguous blocks.
  • Slower Performance: Dynamic memory allocation requires additional processing time for runtime allocation and deallocation.
  • Risk of Memory Overflow: Without proper checks, there is a risk of accessing unallocated or freed memory, leading to errors or crashes.
  • Complexity: Requires careful management of memory allocation, particularly for large programs, making it more complex than static memory allocation.

Frequently Asked Questions

What is the use of malloc in C?

malloc in C is used to dynamically allocate a specified amount of memory at runtime, returning a pointer to the allocated memory block.

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 initialized with 0, while malloc does not initialize 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 Code360 Library

Related Links:

Live masterclass