Allocates space for a group of objects.
#include <stdlib.h> void *_calloc(size_t nmemb, size_t elemsize);
nmemb
number of elements to allocate
elemsize
size of an element
The _ calloc() function allocates contiguous space for nmemb elements of size elemsize. The space is initialized with all bits zero.
_calloc() returns a pointer to the first byte of the memory area allocated. _ calloc() returns a null pointer ( NULL) if no space could be allocated.
#include <stdlib.h> #include <stdio.h> #include <string.h> int main(void) { static char s[] = "woodworking compilers"; char *sptr1, *sptr2, *sptr3; /* Allocate the memory three different ways... */ /* One: allocate a 30-character block of */ /* uninitialized memory. */ sptr1 = (char *) _malloc(30); strcpy(sptr1, s); printf("Address of sptr1: %p\n", sptr1); /* Two: allocate 20 characters of unitialized memory. */ sptr2 = (char *) _malloc(20); printf("sptr2 before reallocation: %p\n", sptr2); strcpy(sptr2, s); /* Re-allocate 10 extra characters */ /* (for a total of 30 characters). */ /* Note that the memory block pointed to by sptr2 is */ /* still contiguous after the call to _realloc(). */ sptr2 = (char *) _realloc(sptr2, 30); printf("sptr2 after reallocation: %p\n", sptr2); /* Three: allocate thirty bytes of initialized memory. */ sptr3 = (char *) _calloc(strlen(s), sizeof(char)); strcpy(sptr3, s); printf("Address of sptr3: %p\n", sptr3); puts(sptr1); puts(sptr2); puts(sptr3); /* Release the allocated memory to the heap. */ _free(sptr1); _free(sptr2); _free(sptr3); return 0; } Output: Address of sptr1: 5e5432 sptr2 before reallocation: 5e5452 sptr2 after reallocation: 5e5468 Address of sptr3: 5e5488 woodworking compilers woodworking compilers woodworking compilers