C calloc
Created By: chatGPT
In C, calloc is a standard library function used to allocate memory for an array of elements. It initializes all bytes in the allocated memory to zero. This is particularly useful when you need to ensure that all elements are set to a default state before use. The syntax of the function is as follows:
void* calloc(size_t num, size_t size);
Here, num represents the number of elements to allocate, and size is the size of each element in bytes. The total memory allocated will be num * size bytes. If the allocation is successful, calloc returns a pointer to the allocated memory. If the allocation fails, it returns NULL.
// Example of using calloc
#include <stdio.h>
#include <stdlib.h>
int main() {
int numElements = 5;
int *array;
// Allocating memory for an array of integers
array = (int*) calloc(numElements, sizeof(int));
// Checking if memory allocation was successful
if (array == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Displaying the values in the allocated array
for(int i = 0; i < numElements; i++) {
printf("Element %d: %d\n", i, array[i]); // All elements initialized to 0
}
// Freeing allocated memory
free(array);
return 0;
}
Important Note: When you use
calloc
, it is essential to deallocate the memory using the free
function once you are done with it to avoid memory leaks. Always check if the memory allocation was successful before proceeding with the use of the allocated memory.// Correctly using free to deallocate memory
free(array);