20
DecDynamic Memory Allocation in C: Malloc(), Calloc(), Realloc(), Free()
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
There are 4 functions to dynamically allocate memory in C language:
- malloc() Function in C
- Callloc() Function in C
- Realloc() Function in C
- Free() Function in C
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
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
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:
%p
format 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
- 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 Allocation | Dynamic 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!