0
0
CHow-ToBeginner · 3 min read

How to Use calloc in C: Syntax, Example, and Tips

In C, calloc is used to allocate memory for an array of elements and initializes all bytes to zero. It takes two arguments: the number of elements and the size of each element, returning a pointer to the allocated memory or NULL if allocation fails.
📐

Syntax

The calloc function allocates memory for an array of elements and initializes all bytes to zero. It requires two parameters:

  • num: Number of elements to allocate.
  • size: Size in bytes of each element.

The function returns a pointer to the allocated memory block or NULL if allocation fails.

c
void *calloc(size_t num, size_t size);
💻

Example

This example shows how to allocate memory for an array of 5 integers using calloc, then prints the initialized values (all zeros), and finally frees the memory.

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

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

    for (int i = 0; i < 5; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    free(arr);
    return 0;
}
Output
arr[0] = 0 arr[1] = 0 arr[2] = 0 arr[3] = 0 arr[4] = 0
⚠️

Common Pitfalls

Common mistakes when using calloc include:

  • Not checking if the returned pointer is NULL, which means allocation failed.
  • Forgetting to free the allocated memory, causing memory leaks.
  • Using malloc when zero-initialization is needed, which leaves memory uninitialized.
  • Mixing up the order of arguments or using incorrect sizes.
c
#include <stdio.h>
#include <stdlib.h>

int main() {
    // Wrong: Not checking for NULL
    int *ptr = (int *)calloc(3, sizeof(int));
    // Using ptr without check can cause crash if allocation fails

    // Right: Check for NULL
    if (ptr == NULL) {
        printf("Allocation failed\n");
        return 1;
    }

    // Use memory safely
    for (int i = 0; i < 3; i++) {
        ptr[i] = i + 1;
        printf("%d ", ptr[i]);
    }
    printf("\n");

    free(ptr);
    return 0;
}
Output
1 2 3
📊

Quick Reference

calloc Cheat Sheet:

  • calloc(num, size): Allocate zero-initialized memory for num elements of size bytes each.
  • Returns void* pointer or NULL if allocation fails.
  • Always check for NULL before using the pointer.
  • Use free() to release memory when done.

Key Takeaways

Use calloc to allocate and zero-initialize memory for arrays.
Always check if calloc returns NULL to avoid crashes.
Remember to free allocated memory to prevent leaks.
Pass the number of elements and size of each element correctly to calloc.
Zero-initialization distinguishes calloc from malloc.