C++ calloc()

The calloc() function returns a pointer to the first byte of the allocated memory block if the allocation succeeds.

If the size is zero, the value returned depends on the implementation of the library. It may or may not be a null pointer.


calloc() prototype

void* calloc(size_t num, size_t size);

The function is defined in <cstdlib> header file.


calloc() Parameters

  • num: An unsigned integral value which represents number of elements.
  • size: An unsigned integral value which represents the memory block in bytes.

calloc() Return value

The calloc() function returns:

  • a pointer to the start of the memory block allocated by the function.
  • null pointer if allocation fails.

Example 1: How calloc() function works?

#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
   int *ptr;
   ptr = (int *)calloc(5, sizeof(int));
   if (!ptr) {
      cout << "Memory Allocation Failed";
      exit(1);
   }
   cout << "Initializing values..." << endl
        << endl;
   for (int i = 0; i < 5; i++) {
      ptr[i] = i * 2 + 1;
   }
   cout << "Initialized values" << endl;
   for (int i = 0; i < 5; i++) {
      /* ptr[i] and *(ptr+i) can be used interchangeably */
      cout << *(ptr + i) << endl;
   }
   free(ptr);
   return 0;
}

When you run the program, the output will be:

Initializing values...

Initialized values
1
3
5
7
9

Example 2: calloc() function with size zero

#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
   int *ptr = (int *)calloc(0, 0);
   if (ptr == NULL) {
      cout << "Null pointer";
   } else {
      cout << "Address = " << ptr << endl;
   }
   free(ptr);
   return 0;
}

When you run the program, the output will be:

Address = 0x371530

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges