C Dynamic Memory Allocation
In C programming, dynamic memory allocation is a way for programs to request memory from the operating system during runtime.
It is useful when the program doesn't know in advance how much memory it will need.
Dynamic memory is allocated on the heap during the program's execution.
It enables the creation of data structures like arrays or linked lists whose size can change during runtime.
It is used for flexiable memory size, efficient memory usage and dynamic data structures.
calloc() Function for Dynamic Memory Allocation
The C standard library provides calloc() function to allocate dynamic memory allocation in the <stdlib.h> header file.
calloc() function allocates memory for an array of elements and initializes all elements to zero.
It is also very crucial to check whether the calloc() function allocates the requested memory. Otherwise it will lead to undefined behavior and your program may crash.
It is very crucial to check whether the calloc() function allocates the requested memory. Otherwise it will lead to undefined behavior. In most cases, this will result in a segmentation fault and your program will crash. Error checking is a fundamental part of writing high-quality software.
Syntax of calloc() Function
num_elements: The number of elements to allocate the memory for
element_size: The size of each element in bytes
Example of calloc() Function
Output of the above example
5 7 9 0
Explanation of code:
-
int* ptr = (int*)calloc(4, sizeof(int));: This line allocates an array of 4 integer elements and initializes all elements to zero. -
if (ptr == NULL): This is a crucial error checking. If calloc() function fails to allocate the requested memory due to some reasons, it will return NULL. -
ptr[0] = 5;...ptr[2] = 9;: These lines assign values to the elements of the dynamically allocated array. No data is assigned to the 4th element intentionally to check the output of unassigned element. -
for (int i = 0; i < 4; i++){...}: This loop iterates through the array and prints each element. -
free(ptr);: The free() function deallocates the memory previously allocated by calloc(). The function takes the pointer ptr as argument. -
ptr = NULL;: Setting the pointer ptr to NULL after freeing it is good practice to avoid dangling pointers.
The free() function is crucial in dynamic memory management process because it deallocates the memory that was previously allocated dynamically. By deallocating memory with free() function, it is ensured that the program uses memory efficiently. In severe cases, memory leaks can exhaust the available memory resources, leading to system instability and crashes.