Dynamic Memory Allocation Using calloc():


In our previous tutorials, we discussed dynamic memory allocation using the malloc()function. In this tutorial, we will explore dynamic memory allocation using the calloc()function. The old C library <stdlib.h>provides the calloc() function for allocating runtime memory.

Similar to the malloc()function, the calloc()function allocates memory dynamically and returns a pointer to the first byte of the memory block of the specified size from the heap. If the requested space is unavailable, it returns NULL.

The main difference between malloc() and calloc() is that malloc() allocates a single block of memory without initializing it to zero, whereas calloc() allocates multiple blocks of memory and initializes them to zero.

The basic syntax for the calloc()function is:

void *calloc(size_t num, size_t size);

In this syntax, numis the number of elements to be allocated, and sizeis the size of each element. The function returns a void pointer to the allocated memory. If insufficient memory is available, it returns NULL.

To return a pointer of a specific type instead of a void pointer, we can use a type cast operator on the return value. The syntax is as follows:

cast_type *ptr; // Pointer to the data type
ptr = (cast_type *)calloc(num, size);
//For Example

int *ptr;
ptr = (int *)calloc(num, sizeof(int));

Let's look at an example to understand how this function works to allocate memory dynamically.

CALLOC() - C++ Copy to Clipboard  
/* Example: Calloc() function */

#include <iostream>
#include <stdlib.h> // Required for calloc() function

using namespace std;

int main() {
    int *ptr, *ptr2; // Ptr to allocate memory and record data, ptr2 to display data
    int num, sum = 0; // num: number of elements, sum: total score to display

    cout << "Enter the total number of elements to store: " << endl;
    cout << "Total elements: ";
    cin >> num;

    ptr = (int *)calloc(num, sizeof(int));
    ptr2 = ptr;
    cout << "\nEnter your " << num << " elements to store: " << endl;

    for (int i = 0; i < num; i++) {
        cout << "Element #" << i << ": ";
        cin >> *ptr;
        sum += *ptr; // Add all entered numbers
        ptr++;
    }

    cout << "\n\nYour elements are: " << endl;
    for (int i = 0; i < num; i++) {
        cout << "Element #" << i << ": " << *ptr2 << endl;
        ptr2++;
    }
    cout << "And the sum is: " << sum << endl;

    return 0;
}

The above example demonstrates a simple use of the calloc()function to allocate memory dynamically. This function allocates enough memory from the heap to store some elements and then returns their sum. If the calloc()function is unable to allocate the requested memory, it returns a NULL pointer, which points to nowhere. Using a NULL pointer can cause the program to crash, so it's important to include an error checker to verify memory allocation. Here's the revised example with an error checker:

CALLOC - C++ Copy to Clipboard  
/* Example: Calloc() function with error checking */

#include <iostream>
#include <stdlib.h> // Required for calloc() function

using namespace std;

int main() {
    int *ptr, *ptr2; // Ptr to allocate memory and record data, ptr2 to display data
    int num, sum = 0; // num: number of elements, sum: total score to display

    cout << "Enter the total number of elements to store: " << endl;
    cout << "Total elements: ";
    cin >> num;

    ptr = (int *)calloc(num, sizeof(int));

    if (ptr == NULL) { // Error Checker
        cout << "Error: calloc() is not able to allocate memory." << endl;
        return 1; // Exit the program with an error code
    }

    ptr2 = ptr;
    cout << "\nEnter your " << num << " elements to store: " << endl;

    for (int i = 0; i < num; i++) {
        cout << "Element #" << i << ": ";
        cin >> *ptr;
        sum += *ptr; // Add all entered numbers
        ptr++;
    }

    cout << "\n\nYour elements are: " << endl;
    for (int i = 0; i < num; i++) {
        cout << "Element #" << i << ": " << *ptr2 << endl;
        ptr2++;
    }
    cout << "And the sum is: " << sum << endl;

    // Free the allocated memory
    free(ptr2);

    return 0;
}