C++ calloc()

The calloc() function in C++ allocates a block of memory for an array of objects and initializes all its bits to zero.

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 malloc() function works?

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

int main()
{
    int *ptr;
    ptr = (int*) malloc(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: malloc() function with size zero

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

int main()
{
    int *ptr = (int*) malloc(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