0
0
Cprogramming~5 mins

calloc function

Choose your learning style9 modes available
Introduction

The calloc function helps you get memory for multiple items and sets all that memory to zero. This makes sure the memory is clean and ready to use.

When you need to create an array of items and want all values to start at zero.
When you want to avoid garbage or random data in new memory before using it.
When you need memory for multiple objects and want it automatically cleared.
When you want to safely allocate memory for a structure or block without manual initialization.
Syntax
C
void *calloc(size_t num_items, size_t size_of_item);

num_items is how many items you want.

size_of_item is the size in bytes of each item.

Examples
This creates space for 5 integers and sets all to zero.
C
int *arr = (int *)calloc(5, sizeof(int));
This creates space for 100 characters, all set to zero (null characters).
C
char *buffer = (char *)calloc(100, sizeof(char));
This creates space for 10 Point structures, all bytes zeroed.
C
struct Point *points = (struct Point *)calloc(10, sizeof(struct Point));
Sample Program

This program creates an array of 4 integers using calloc. It then prints the values, which are all zero because calloc clears the memory. Finally, it frees the memory.

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

int main() {
    int n = 4;
    int *arr = (int *)calloc(n, sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    printf("Array values after calloc:\n");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    free(arr);
    return 0;
}
OutputSuccess
Important Notes

Always check if calloc returns NULL, which means memory allocation failed.

Remember to use free() to release the memory when done to avoid memory leaks.

calloc differs from malloc because it clears the memory to zero.

Summary

calloc allocates memory for multiple items and sets all bytes to zero.

Use it when you want clean, zeroed memory for arrays or structures.

Always check for NULL and free the memory after use.