Namespaces
Variants
Views
Actions

calloc

From cppreference.com
< c‎ | memory
Defined in header <stdlib.h>
void* calloc( size_t num, size_t size );

Allocates memory for an array of num objects of size size and initializes all bits in the allocated storage to zero.

If allocation succeeds, returns a pointer to the lowest (first) byte in the allocated memory block that is suitably aligned for any object type.

If size is zero, the behavior is implementation defined (null pointer may be returned, or some non-null pointer may be returned that may not be used to access storage)

calloc is thread-safe: it behaves as though only accessing the memory locations visible through its argument, and not any static storage.

A previous call to free or realloc that deallocates a region of memory synchronizes-with a call to calloc that allocates the same or a part of the same region of memory. This synchronization occurs after any access to the memory by the deallocating function and before any access to the memory by calloc

(since C11)

Contents

[edit] Parameters

num - number of objects
size - size of each object

[edit] Return value

Pointer to the beginning of newly allocated memory or NULL if error has occurred. The pointer must be deallocated with free().

[edit] Notes

Due to the alignment requirements, the number of allocated bytes is not necessarily equal to num*size.

Initialization to all bits zero does not guarantee that a floating-point or a pointer would be initialized to 0.0 and the null pointer value, respectively (although that is true on all common platforms)

[edit] Example

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    /* Allocate an array of four integers. */
    /* Initialize all elements to 0.       */
    int *pa = calloc(4,sizeof(int));
    if (pa == NULL) {
       printf("calloc() failed in file %s at line # %d", __FILE__,__LINE__);
       exit(1);
    }
 
    /* Print one of the array elements. */
    printf("pa[3] = %d\n", pa[3]);
 
    /* Deallocate array pa. */
    free(pa);
    return 0;
}

Possible output:

pa[3] = 0

[edit] See also