How to use calloc() in C++

In C++, we can use the calloc() function to allocate a block of memory. This allocated memory can be used for an array of objects, and all the bits are initialized to zero.

Syntax

void* calloc(size_t num, size_t size);

num

This represents the number of elements for which the memory block is allocated. It is an unsigned integral value.

size

This represents the size of each element in the allocated memory block in bytes. It is an unsigned integral value.

size_t is an unsigned integral type.

Return value

The method calloc() returns the following cases:

  • A pointer to the first byte of the allocated memory block if allocation is successful.

  • A null pointer if allocation is failed.

calloc() returns void. In order to convert it into other data type, we use typecasting.

Required headers

#include <cstdlib>

Code

//Including headers
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
//Allocating memory block
int* ptr = (int*)calloc(10, sizeof(int));
//Checking for failure
if (!ptr) {
cout << "Failed to allocated memory\n";
exit(1);
}
//Initializing allocated memory
for (int i = 0; i < 10; i++) {
ptr[i] = i;
}
//Printing allocated memory
for (int j = 0; j < 10; j++) {
cout << *(ptr + j) << endl;
}
//ptr[i] and *(ptr+i) are same
//Deallocating allocated memory
free(ptr);
return 0;
}

Free Resources