Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Dynamic Memory Allocation in C: Malloc(), Calloc(), Realloc(), Free()

Dynamic Memory Allocation in C: Malloc(), Calloc(), Realloc(), Free()

27 May 2024
Advanced
13.7K Views
13 min read
Learn with an interactive course and practical hands-on labs

C Programming Free Course with Certificate: Learn C In 21 Days

Dynamic Memory Allocation Example: An Overview

Are you a beginner looking to understand how dynamic memory allocation works in C? This article, C for beginners, will serve as a valuable resource to help you grasp dynamic memory allocation. You can go for a C course if you want to deepen your knowledge and expertise in this area. This article covers when and where to allocate memory for variables, understanding static vs. dynamic allocations, and freeing resources correctly.

What is Dynamic Memory Allocation in C?

We saw in previous sections how we declare variables to get the memory space required for our program. But is it always known to the programmer how much memory will he require to run the program? What if you want memory space during the program execution? What if your declared array size becomes insufficient or is more than required? All these scenarios are handled here.

The header file stdlib.h is used for the purpose of dynamic memory allocation. With the help of dynamic memory allocation, you can allocate memory to the program during run time. It makes it possible to optimize memory usage in a program and reduce the risk of memory leaks.

Functions used for Dynamic Memory Allocation in C

Functions used for Dynamic Memory Allocation in C

There are 4 functions to dynamically allocate memory in C language:

  1. malloc() Function in C
  2. Callloc() Function in C
  3. Realloc() Function in C
  4. Free() Function in C

  1. malloc() function

It allocates a single block of memory based on user-specified size. It returns null if memory is not sufficient. It's important to keep in mind that malloc() returns a pointer to the beginning of the newly allocated memory block, and it's the programmer's responsibility to free this memory when it's no longer needed.

Read More - Top 50 Mostly Asked C Interview Questions and Answers

Syntax

ptr=(cast-type*)malloc(byte-size)

malloc() function Example


#include<stdio.h> 
#include<stdlib.h> 
int main()
{ 
 int n,i,*ptr,sum=0; 
 printf("Enter the number of elements: "); 
 scanf("%d",&n); 
 ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc 
 if(ptr==NULL) 
 { 
 printf("Unable to allocate memory"); 
 exit(0); 
 } 
 printf("Enter elements of array: "); 
 for(i=0;i<n;++i) 
 { 
 scanf("%d",ptr+i); 
 sum+=*(ptr+i); 
 } 
 printf("Sum=%d",sum); 
 free(ptr); 
 return 0; 
} 

Here, malloc() function creates an array of given size “n” during run time. The size value is stored in a pointer.

Output

Enter the number of elements: 5
Enter elements of the array: 10 20 30 40 50
Sum = 150

  1. calloc() function

It not only reserves the requested amount of memory but also initializes those bytes to 0. It allocates multiple blocks of memory. It returns null if memory is not sufficient.

It's important to keep in mind that calloc() returns a pointer to the beginning of the newly allocated memory block, and it's the programmer's responsibility to free this memory when it's no longer needed.

Syntax

ptr=(cast-type*)calloc(number, byte-size) 

calloc() function Example


#include<stdio.h> 
#include<stdlib.h> 
int main(){ 
int n,i,*ptr,sum=0; 
 printf("Enter the number of elements: "); 
 scanf("%d",&n); 
 ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc 
 if(ptr==NULL) 
 { 
 printf("Unable to allocate memory"); 
 exit(0); 
 } 
 printf("Enter the elements of array: "); 
 for(i=0;i<n;++i) 
 { 
 scanf("%d",ptr+i); 
 sum+=*(ptr+i); 
 } 
 printf("Sum=%d",sum); 
 free(ptr); 
 return 0; 
}
Here, calloc() function creates an array of given size “n” during run time. The size value is stored in a pointer.

Output

Enter the number of elements: 5
Enter the elements of array: 10 20 30 40 50
Sum = 150

  1. realloc() function

This allows a programmer to adjust the size of previously allocated memory dynamically, making it a valuable tool for optimizing memory usage.

  • The realloc() function works by allocating a new block of memory with the desired size, copying the contents of the old block into the new one, and finally freeing the old block.

Syntax

ptr=realloc(ptr, new-size)

realloc() function Example


#include <stdio.h>
#include <stdlib.h>
int main()
{
 int *ptr, i , n1, n2;
 printf("Enter the number of elements to declare size required: ");
 scanf("%d", &n1);
 ptr = (int*) malloc(n1 * sizeof(int)); //memory allocated using malloc()
 printf("Addresses of previously allocated memory:\n");
 for(i = 0; i < n1; ++i)
 {
 printf("%p\n",ptr + i);
 }
 printf("\nEnter the number of elements to declare the new size required: ");
 scanf("%d", &n2);

 // rellocating the memory
 ptr = realloc(ptr, n2 * sizeof(int));
 printf("Addresses of newly allocated memory:\n");
 for(i = 0; i < n2; ++i)
 { 
 printf("%p\n", ptr + i);
 }
 free(ptr);
 return 0;
}
  • Here, the program in the C Editor first creates a memory of size n1 using malloc() function. It prints the addresses of the allocated memory.
  • Afterwards it increases the previous size to n2 using realloc() function. It then prints the addresses of the newly allocated memory.
  • Note: %pformat specifier is used to print the address/pointer.

Output

Enter the number of elements to declare size required: 5
Addresses of previously allocated memory:
0x7fb3e4801000
0x7fb3e4801004
0x7fb3e4801008
0x7fb3e480100c
0x7fb3e4801010

Enter the number of elements to declare the new size required: 7
Addresses of newly allocated memory:
0x7fb3e4801000
0x7fb3e4801004
0x7fb3e4801008
0x7fb3e480100c
0x7fb3e4801010
0x7fb3e4801014
0x7fb3e4801018

  1. free() function

In the above functions, we saw that the memory allocated dynamically using malloc(), calloc(), and realloc() is being freed at the the end of the program. The free() function in C is a powerful tool that enables programmers to release previously allocated dynamic memory. This function is particularly useful in managing memory in large applications developed in C.

  • With the free() function, programmers can reallocate memory to different functions when required, without worrying about overwriting important data or causing system crashes.
  • In addition, this function helps prevent memory leaks that can cause the system to slow down or crash completely.

Syntax

free(ptr);

Difference Between Static and Dynamic Memory Allocation in C

Static Memory AllocationDynamic Memory Allocation
Allocation is done for the duration of the program's execution or the duration of the function call.Allocation is done when your program starts executing.
Prior to program execution, static memory allocation is performed.Program execution includes dynamic memory allocation.
For controlling the static allocation of memory, it makes use of stack.It uses a heap to control the dynamic memory allocation.
It is less productive.It is more productive.
There is no memory reuse in static memory allocation.When not needed, memory can be released and re-used in dynamic memory allocation.
Once memory has been allocated in a static allocation, its size cannot be changed.When memory is allocated dynamically, the memory size may be modified.
The unused memory cannot be used again in this memory allocation mechanism.When necessary, the user can allocate more RAM. Additionally, the user has the option of releasing memory as necessary.
Summary

Dynamic memory allocation is a crucial aspect of C programming, empowering developers to create more efficient and flexible applications. By mastering these techniques and following best practices, you can harness the full potential of dynamic memory allocation while maintaining the integrity and stability of your C programs.

However, if you're seeking to validate your expertise and demonstrate your proficiency in C programming, pursuing a C Course can be a valuable step. With these skills in hand, understanding strings in C should become a breeze!

FAQs

Yes, dynamic memory allocation may be unsuccessful if there is not enough memory in the system to accommodate the requested allocation. Functions like malloc() or calloc() would return a NULL pointer in such circumstances.

Due to memory fragmentation and the requirement for explicit allocation and deallocation, dynamic memory allocation can have an adverse effect on performance. This may result in reduced processing speeds and more difficult memory management.

Yes, dynamic memory allocation, which allows for dynamic scaling and offers flexibility in memory utilization, is frequently used for arrays and structures. In contrast, stack-based memory allocation uses a last-in-first-out (LIFO) structure and has size restrictions.

While stack-based allocation is faster but has size and scope restrictions, dynamic allocation in c uses the heap and enables more flexible memory management. While stack-based allocation is handled automatically, dynamic allocation requires deliberate memory deallocation via free.

Always combine dynamic memory allocation with appropriate deallocation using the free() function once the allocated memory is no longer required to avoid memory leaks. Use effective memory management techniques and think about employing tools to find memory leaks.

malloc() and calloc() returns a NULL pointer if they are unable to allocate memory because there is not enough free memory. Before using the memory that has been allocated, it is essential to validate this return value to avoid program crashes and unexpected behavior.
Share Article
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this