C++ <cstdlib> - calloc() Function
The C++ <cstdlib> calloc() function is used to allocate a block of memory for an array of num elements of size bytes long, and initializes all its bits to zero. If allocation succeeds, it returns a pointer to the lowest (first) byte of newly allocated memory.
If size is zero, the behavior of the function is implementation-defined (it may or may not be a null pointer), but the returned pointer shall not be dereferenced, and should be passed to free() to avoid memory leaks.
Syntax
void* calloc (size_t num, size_t size);
Parameters
num |
Specify number of elements to allocate. size_t is an unsigned integral type. |
size |
Specify size of each element. size_t is an unsigned integral type. |
Return Value
On success, returns a pointer to the lowest (first) byte of newly allocated memory. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable. On failure, returns a null pointer.
Example:
The example below shows the usage of <cstdlib> calloc() function.
#include <cstdio> #include <cstdlib> int main (){ //allocating memory for array of 5 int int *p1 = (int*) calloc(5, sizeof(int)); //another way of doing the same int *p2 = (int*) calloc(1, sizeof(int[5])); //another way of doing the same int *p3 = (int*) calloc(5, sizeof *p3); //displaying the array for(int i=0; i<5; i++) printf("p1[%d] = %d\n", i, p1[i]); //deallocating previously allocated memory free(p1); free(p2); free(p3); return 0; }
The output of the above code will be:
p1[0] = 0 p1[1] = 0 p1[2] = 0 p1[3] = 0 p1[4] = 0
❮ C++ <cstdlib> Library