Zone Of Makos

Menu icon

calloc in C

In the C programming language, calloc is a library function used for dynamically allocating memory. It is similar to the malloc function but with an additional feature of initializing the allocated memory to zero. The name calloc stands for "contiguous allocation."

Syntax of calloc

The syntax for using calloc is as follows:


void* calloc(size_t num, size_t size);

The calloc function takes two arguments: num and size . The num parameter specifies the number of elements to allocate, and the size parameter specifies the size of each element in bytes. The total amount of memory allocated is num * size .

Example Usage

Here's an example that demonstrates how to use calloc to allocate memory for an array of integers and initialize it to zero:


#include <stdio.h>
#include <stdlib.h>

int main() {
    int* numbers;
    int numElements = 5;
    
    numbers = (int*)calloc(numElements, sizeof(int));
    
    if (numbers == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }
    
    for (int i = 0; i < numElements; i++) {
        printf("%d ", numbers[i]);  // Prints 0 for each element
    }
    
    free(numbers);
    
    return 0;
}

In this example, we allocate memory for an array of numElements integers using calloc . The sizeof(int) is used to determine the size of each integer element. The allocated memory is then assigned to the numbers pointer.

We check if the memory allocation was successful by verifying if numbers is equal to NULL . If it is NULL , it means that the allocation failed, and we display an error message.

Finally, we print the elements of the allocated array, which should all be initialized to zero because of the use of calloc . After we're done using the allocated memory, we free it using the free function to release the allocated memory back to the system.

Conclusion

The calloc function in C is a useful tool for allocating dynamic memory and initializing it to zero. It provides a convenient way to allocate memory for arrays or structs and ensures that the allocated memory is initialized properly. Just remember to free the allocated memory using the free function when you're done using it to avoid memory leaks.