21
NovHow to Dynamically Allocate Memory using calloc() in C?
calloc() Function in C
calloc() function in C is one of the powerful functions used for Dynamic Memory Allocation in C programming. It is defined inside stdlib.h header file. It allocates multiple blocks of memory with the same size for each block.
In this C Tutorial, we'll try to understand calloc() function in C language, the syntax of calloc() function in C, the advantages and disadvantages of calloc() function in C, and much more. Before that, do check out what is malloc() function in C, and if you're a beginner to C, get enrolled in our C Programming Certification Training to learn from scratch.
Read More: Top 50 Mostly Asked C Interview Questions and Answers
What is calloc() in C?
calloc() is one of those functions used in dynamically allocating memory in C programming. Firstly, 'calloc' stands for 'contiguous allocation' and it is used to allocate memory for arrays, it allocates memory in specified sizes and then initializes that allocated block of memory to zero.
Syntax of calloc() Function in C
The simple syntax of calloc() function in C looks like this:
void *calloc(size_t num_elements, size_t element_size);
Parameters of calloc() Function in C
- num_elements- Elements that need memory to be allocated for are represented by num_elements parameter.
- element_size- The size is represented by element_size. The size will be in bytes.
- size_t- It is an integer type that is unsigned and it can hold the size of any object in bytes.
Return Value of calloc() Function in C
- If the memory was successfully allocated, it returns a pointer to the block of that memory.
- If the memory allocation fails by any chance, it will return NULL.
Read More: Beginner's Guide to C Programming
Calloc() Function in C library with EXAMPLE
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int num_elements = 5;
// Allocating memory for an array of 5 integers
arr = (int *)calloc(num_elements, sizeof(int));
if (arr == NULL) {
fprintf(stderr, "Memory allocation failed\n");
return 1; // Return error code
}
// Printing the allocated array (should be initialized to zero)
printf("Allocated array:\n");
for (int i = 0; i < num_elements; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Modifying the elements of the array
for (int i = 0; i < num_elements; i++) {
arr[i] = i + 1;
}
// Printing the modified array
printf("Modified array:\n");
for (int i = 0; i < num_elements; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Freeing the allocated memory
free(arr);
return 0; // Return success code
}
Explanation:
- We have used calloc() function for allocating memory of a 5 integer array.
- An integer pointer arr was defined earlier, we use it to check if the allocation was successful or not.
- We have then printed the allocated array, it will have all zeros at initial point due to the factor that calloc() initialises memory to zero. After modifying it will show the new values.
- At last, we have to free up the memory that was allocated with the help of free() function.
Output
Allocated array:
0 0 0 0 0
Modified array:
1 2 3 4 5
Advantages of Calloc() in C Programming
- A major advantage of using calloc() function is that the allocated block of memory is initialized to zero. The reason why initialization is important is that it makes sure that the memory is in a consistent state and is predictable.
- With the help of calloc() function, developers can easily allocate memory for arrays without the need to initialize each element to zero so it is best for memory allocation of arrays.
- There is no risk of accessing an initialized memory as calloc() already provides initialization to zero.
- Error handling is easier with the help of calloc() as it will return NULL if the allocation process fails so the failures can be easily checked and handled.
- calloc() also provides cross platform compatibility and is available in mostly all C implementations.
Disadvantages of Calloc() in C Programming
- The automatic initialization in calloc() function makes it slower as compared to other functions such as malloc().
- The initial allocation of memory to zero leads to wastage of memory usage, which might not be the case in functions that require manual initialization which can be done only when needed.
- It is limited to only arrays for memory allocation.
- Error handling is, many a times, a complex process while working with calloc().
Difference Between Static and Dynamic Memory Allocation
Static Memory Allocation | Dynamic Memory Allocation |
In static memory allocation, memory allocation happens at compile time. | In dynamic memory allocation, memory allocation happens during the execution of the program. |
Usually, compiler is the one that automatically handles the memory management. | Developers need to manually allocate and deallocate memory with the help of functions like malloc(), calloc(), realloc(), free(). |
The value of variables remains throughout the execution of the program. | The blocks of memory are created and destroyed as per the requirement. |
It is comparatively faster in terms of performance. | The performance is slower due to manual allocation and deallocation process. |
Static allocation provides variables with global scope or file scope. | Dynamic memory allocation allows for various scopes based on its usage and accessibility. |
Program to check Dynamic Memory Allocation using calloc() function
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int num_elements = 5;
// Allocate memory using calloc
ptr = (int *)calloc(num_elements, sizeof(int));
// Check if memory allocation was successful
if (ptr == NULL) {
printf("Memory allocation failed\n");
} else {
printf("Memory allocated successfully\n");
// Use the allocated memory
for (int i = 0; i < num_elements; i++) {
ptr[i] = i + 1; // Assign values to the allocated memory
}
// Print the allocated memory values
printf("Allocated memory values:\n");
for (int i = 0; i < num_elements; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
// Free the allocated memory
free(ptr);
printf("Memory freed successfully\n");
}
return 0;
}
Explanation:
- In the above program, we have used calloc() to allocate memory for a 5 integer array.
- We have already defined an integer pointer ptr to check if allocation was successful or not by checking if ptr is 'NULL'.
- If it was successful, we can use the allocated memory to assign values and print.
- Finally, using free()function we have freed the allocated memory.
Output
Memory allocated successfully
Allocated memory values:
1 2 3 4 5
Memory freed successfully
Program to demonstrate the use of the calloc() function
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int num_elements, sum = 0;
// Ask the user to enter the number of elements
printf("Enter the number of elements: ");
scanf("%d", &num_elements);
// Allocate memory for an array of integers using calloc
arr = (int *)calloc(num_elements, sizeof(int));
// Check if memory allocation was successful
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1; // Return error code
}
// Ask the user to enter the elements of the array
printf("Enter %d elements:\n", num_elements);
for (int i = 0; i < num_elements; i++) {
scanf("%d", &arr[i]);
}
// Compute the sum of the elements
for (int i = 0; i < num_elements; i++) {
sum += arr[i];
}
// Print the sum of the elements
printf("Sum of the elements: %d\n", sum);
// Free the allocated memory
free(arr);
return 0; // Return success code
}
Output
Enter the number of elements: 5
Enter 5 elements:
10
20
30
40
50
Sum of the elements: 150
Summary
FAQs
void *calloc(size_t num_elements, size_t element_size);
int *ptr1 = (int *)malloc(5 * sizeof(int)); // Allocates memory for an array of 5 integers int *ptr2 = (int *)calloc(5, sizeof(int)); // Allocates memory for an array of 5 integers initialized to zero