Do you think IIT Guwahati certified course can help you in your career?
No
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.
Dynamic memory allocation 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.
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;
}
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;
}
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;
}
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
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;
}
Difference between Static Memory Allocation and Dynamic Memory Allocation
Parameters
Static Memory Allocation
Dynamic Memory Allocation
Memory Allocation Time
Memory is allocated at compile time.
Memory is allocated at runtime.
Memory Size
Fixed size determined during compile time.
Size can be changed during program execution.
Flexibility
Less flexible, memory size cannot be changed.
More flexible, memory size can be adjusted dynamically.
Memory Deallocation
No manual deallocation; memory is released after program ends.
Memory must be manually deallocated using free().
Memory Management
Managed by the compiler.
Managed by the programmer.
Example
int arr[10];
int* arr = (int*)malloc(10 * sizeof(int));
Efficiency
Faster due to compile-time allocation.
Slower due to runtime allocation and management.
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 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.
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.