Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

calloc — C23 allocation function

`calloc(nmemb, size)` from `<stdlib.h>` allocates an array of `nmemb` objects of `size` bytes, sets every bit of the allocated region to zero, and returns its pointer or null. C23 also requires null when the product `nmemb * size` would wrap `size_t`.

Version: C23

Syntax

void *calloc(size_t nmemb, size_t size);

calloc(nmemb, size) from <stdlib.h> allocates an array of nmemb objects of size bytes, sets every bit of the allocated region to zero, and returns its pointer or null. C23 also requires null when the product nmemb * size would wrap size_t.

Use it for a dynamically allocated array whose representation must start zeroed. The example allocates four int objects, checks failure, genuinely reads the four initial zeros, and releases that exact block with free.

All-bits-zero need not represent floating 0.0 or a null pointer, so calloc is not universal typed initialization. For a zero-size request an implementation may return null or a special pointer that must not be used to access an object; check null before access and free any successful allocation.

Examples

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *values = calloc(4, sizeof *values);
    if (values == NULL) return 1;
    printf("%d %d %d %d\n", values[0], values[1], values[2], values[3]);
    free(values);
    return 0;
}

Result

0 0 0 0

Use it for a dynamically allocated array whose representation must start zeroed. The example allocates four `int` objects, checks failure, genuinely reads the four initial zeros, and releases that exact block with `free`.

Sources