Dynamic Memory Allocation In C [Explained With Examples]
Hello Friends In today’s article we are going to talk about Dynamic Memory Allocation In C Language
Today we will learn in detail about what is dynamic memory allocation In C and how to do dynamic memory allocation in C language.
So now let’s first understand what is Dynamic Memory Allocation In C.
What is Dynamic Memory Allocation in C
Dynamic memory allocation is a method with the help of which in C language we can allocate memory at the time of program execution (in runtime).
C is a structured programming language which has some fixed rules for programming. One of the rules is related to Array.
Array is a group of many elements in which memory is allocated to all the elements in contiguous form. In C language, once the size of the array is declared, it cannot be changed later.
For Example -: Suppose we have an array of 9 elements in our program and if we need only 5 elements in the program, then the memory received by the rest of the array elements will be wasted.
Also, if 9 array elements in the program become full and we need 5 more extra elements, then we will not be able to increase the size of the array from 9 to 14.
In such a situation, the concept of Dynamic Memory Allocation came to solve this problem.
In Dynamic Memory Allocation, we can allocate memory of as much size as is required during program execution.
The memory management functions (malloc(), calloc(), realloc() and free() ) are used for memory allocation and deallocation (freeing up memory). These functions are defined in the <stdlib.h> header files.
Pointer is used to manage and access dynamic memory, in C language you cannot do dynamic memory allocation without pointer because Pointer is the only variable that will be able to point the address of that dynamic memory and will be able to access that dynamic memory.
You can learn about pointer in detail from here -:
Let us now learn about the memory management functions (malloc(), calloc(), realloc() and free() ) in detail one by one.
Function | Syntax |
malloc() | malloc (number *sizeof(int)); |
calloc() | calloc (number, sizeof(int)); |
realloc() | realloc (pointer_name, number * sizeof(int)); |
free() | free (pointer_name); |
1) malloc() function in C
The malloc() function is used to allocate memory dynamically at the time of program execution. The dynamic memory allocated with the help of malloc() function has a garbage value by default.
When the malloc() function does not allocate the required memory, then it returns a NULL pointer.
Syntax -:
ptr=(cast-type*)malloc(byte-size)
For Example -:
ptr = (int*) malloc(100 * sizeof(int));
The size of int is 4 bytes and in this above example, we have allocated 400 bytes of dynamic memory by doing malloc(int*) malloc(100 * sizeof(int));
Here the ptr pointer holds the first address of this 400-byte memory and as we know the pointer, whichever address it holds, it points to it.
Note – If there is not enough space in computer memory as demanded during dynamic memory allocation then it returns NULL pointer.
Let’s understand the malloc() function better through an example.
Example -:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr;
printf("Enter number of elements: ");
scanf("%d",&n);
//memory allocated using malloc
ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
else
{
printf("Memory successfully allocated using malloc.\n");
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
}
}
free(ptr);
return 0;
}
Output -:
Enter number of elements: 5
Memory successfully allocated using malloc
Enter elements of array:
10
20
30
40
50
In this example, we take input a number from the user, then we allocated the same size space dynamically in memory.
The address of this dynamic memory holds the ptr pointer, which will be destroyed with the end of this program, so we have to free the memory space received by this dynamic memory, or else the memory will be lost.
The free() function is used to free dynamic memory, we will know about this free() function in further detail, now we learn about the calloc() function.
2) calloc() function in C
With the help of calloc() function, we can dynamically allocate many blocks of memory. It is used to allocate memory for complex data structures such as arrays and structures.
It allocates memory dynamically like malloc() function but calloc() is used to allocate multiple blocks of memory space and malloc() is used to allocate single block of memory space.
Dynamic memory created with the help of malloc() has garbage value by default whereas dynamic memory created with the help of calloc() is initialized to zero by default.
If there is not enough space in the memory while allocating dynamic memory with the help of calloc() function then it returns Null.
Syntax -:
ptr = (cast-type*)calloc(n, element-size);
Here n, number of elements and element size tells what will be the size of each element.
For Example -:
ptr = (float*) calloc(25, sizeof(float));
This statement will allocate 25 elements in memory and the size of each element will be equal to the size of float data type.
Let’s understand the calloc() function with an example.
Example -:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr;
printf("Enter number of elements: ");
scanf("%d",&n);
//memory allocated using calloc
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
else
{
printf("Memory successfully allocated using calloc.\n");
}
free(ptr);
return 0;
}
Output -:
Enter number of elements: 5
Memory successfully allocated using calloc
In this example, we have taken a number input from the user for the size of the memory that we want to allocate and checked whether the memory is allocated or not by an if condition.
3) realloc() function in C
realloc() is used to change the size of dynamic memory created with the help of malloc() or calloc(). With the help of realloc() function, we can easily change the size of dynamic memory.
If we want to increase or decrease the size of dynamic memory then we use realloc() function.
Syntax of realloc() Function -:
ptr=realloc(ptr, new-size)
Here ptr will be reallocated with the new size.
Example -:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr, n, i;
// Get the number of elements for the array
printf("Enter a Number");
scanf("%d", &n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully allocated by malloc or not
if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
printf("Enter number of elements: %d\n", n);
for (i = 0; i < n; ++i)
{
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
// Get the new size for the array
n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));
printf("Memory successfully re-allocated using realloc.\n");
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}
Output -:
Enter a number 3
Memory successfully allocated using calloc.
Enter number of elements: 3
The elements of the array are: 1, 2, 3
Enter the new size of the array: 10
Memory successfully re-allocated using realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
In this example, we take input a number from the user, and then according to that we dynamically allocate memory with the help of malloc() function. We later changed the size of this dynamic memory to 10 with the help of realloc() function.
4) free() function in C
The free() function is used to deallocate or release the dynamic memory created with the help of malloc() or calloc() functions.
By free() function we prevent memory loss, if we do not use free() function to release or deallocate dynamically allocated memory, then this memory will remain reserve whether it is used in program or not.
Syntax -:
free(ptr);
Here prt is a pointer variable which points to the dynamic memory space. We are releasing the dynamically allocated memory with the help of this pointer variable and free() function.
Example -:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
// deallocating the memory
free(ptr);
return 0;
}
Conclusion
Friends, I hope you have found the answer to your question and you will not have to search about what is dynamic memory allocation In C and how to do dynamic memory allocation in C language.
However, if you want any information related to this post or related to programming language, or computer science, then comment below I will clear your all doubts
If you want a complete tutorial on C language, then see here C Language Tutorial. Here you will get all the topics of C Programming Tutorial step by step.
Friends, if you liked this post, then definitely share this post with your friends so that they can get information about dynamic memory allocation In C
To get the information related to Programming Language, Coding, C, C ++, subscribe to our website newsletter. So that you will get information about our upcoming new posts soon.