6.19.14 calloc Function
Dynamically allocate and clear a block of memory from the heap for an array of objects.
Include
<stdlib.h>
Prototype
void * calloc(size_t nelem, size_t size);
Arguments
nelem
- number of array elements
size
- size of each element
Return Value
Returns a pointer to the allocated space if successful; otherwise, returns a null pointer.
Remarks
Although the memory block allocated and whose address is returned will be large enough to hold an object with the specified size, the memory required to allocate that block might be larger than the requested size due to alignment of the allocated memory, and/or additional objects that are used to manage the heap.
Unlike malloc
, the calloc
function initializes the memory
it allocates to 0.
See your MPLAB XC compiler User's Guide for more information on dynamic memory allocation.
Example
/* This program allocates memory for the */
/* array 'i' of long integers and initializes */
/* them to zero. */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int x;
long *i;
i = (long *)calloc(5, sizeof(long));
if (i != NULL)
{
for (x = 0; x < 5; x++)
printf("i[%d] = %ld\n", x, i[x]);
free(i);
}
else
printf("Cannot allocate memory\n");
}
Example Output
i[0] = 0
i[1] = 0
i[2] = 0
i[3] = 0
i[4] = 0