User Tools

Site Tools


Sidebar

Programming Reference/Librarys

Question & Answer

Q&A is closed







c:stdlib.h:calloc

calloc

    #include <stdlib.h>
    void *calloc(size_t nitems, size_t size); 

description

The calloc() function shall allocate unused space for an array of nelem elements each of whose size in bytes is elsize.
The space shall be initialized to all bits 0.

The order and contiguity of storage allocated by successive calls to calloc() is unspecified.
The pointer returned if the allocation succeeds shall be suitably aligned so that it may be assigned to a
pointer to any type of object and then used to access such an object or an array of such objects in the space
allocated (until the space is explicitly freed or reallocated). Each such allocation shall yield a pointer to an object disjoint
from any other object. The pointer returned shall point to the start (lowest byte address) of the allocated space.
If the space cannot be allocated, a null pointer shall be returned. If the size of the space requested is 0, the behavior
is implementation-defined: the value returned shall be either a null pointer or a unique pointer.

return value

Upon successful completion with both nelem and elsize non-zero, calloc() shall return a pointer to the allocated space.
If either nelem or elsize is 0, then either a null pointer or a unique pointer value that can be successfully passed to free() shall be returned.
Otherwise, it shall return a null pointer and set errno to indicate the error.

calloc C Sourcecode Example

/* 
 * calloc example code
 * http://code-reference.com/c/stdlib.h/calloc
 */
 
#include <stdio.h> /* including standard library */
//#include <windows.h> /* uncomment this for Windows */
 
#include <stdlib.h>
 
int main( void)
{
    int newsize, *ptr;
 
     printf("Enter the number of type int to allocate: ");
     scanf("%d", &newsize);
 
     ptr = calloc(newsize, sizeof(int));
 
     if (ptr != NULL) {
         printf("allocation of memory was successfully.\n");
     }
     else {
          printf("allocation of memory failed.\n");
     }
 
return 0;
}

Output

  Output allocation successfully:
  user@host:~$  ./calloc 
  Enter the number of type int to allocate: 2345
  allocation of memory was successfully.
  Output allocation failed:
  user@host:~$  ./calloc 
  Enter the number of type int to allocate: 9992992992
  allocation of memory failed.

on the occasion of the current invasion of Russia in Ukraine

Russian Stop this War
c/stdlib.h/calloc.txt · Last modified: 2024/02/16 01:04 (external edit)

Impressum Datenschutz