calloc() in C - Source Code Example

In this source code example, we will see how to use the calloc() function in C programming with an example.

calloc() Function Overview

The calloc() function in C stands for "contiguous allocation". It's used to allocate memory for an array of specified elements, each of a specified size. 

The main difference between malloc and calloc is that calloc initializes all the allocated memory to zero. It's also part of the <stdlib.h> library. 

Like malloc, memory allocated using calloc must be released with free() to avoid memory leaks.

Source Code Example

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

int main() {
    int *arr;
    int n, sum = 0;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    // Allocating and initializing memory for 'n' integers
    arr = (int*)calloc(n, sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed!");
        exit(1);
    }

    printf("Enter %d integers:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // Calculating the sum of the integers
    for (int i = 0; i < n; i++) {
        sum += arr[i];
    }

    printf("Sum = %d\n", sum);

    // Releasing the allocated memory
    free(arr);

    return 0;
}

Output

Enter number of elements: 3
Enter 3 integers:
10 20 30
Sum = 60

Explanation

1. We start by asking the user to define the number of integers they want to input.

2. We utilize calloc to allocate and initialize a block of memory that can house 'n' integers. Since it's calloc, this memory is initialized to zero.

3. We make sure the memory allocation is successful. If it isn't, we display an error message and terminate the program.

4. We then prompt the user to input 'n' integers.

5. We store these integers in our memory block and then calculate and display their collective sum.

6. Lastly, to prevent any memory leaks, we release the memory we allocated with free().


Comments