Function Description

  • prototype: void * Calloc (unsigned int num, unsigned int size; calloc

  • Function: Assign NUM lengths in the dynamic storage area of ​​the memory: "

  • Note: Num: Objects, Size: Object occupied memory byte number , Compared to the malloc function, the Calloc function will automatically initiate the memory into 0;

Difference to Malloc

Calloc after dynamic distribution Automatically initialize the memory space is zero, while Malloc does not initialize, the data in the assigned space is random data. The description of Malloc is as follows:

  • prototype: Extern void * malloc (unsigned int size);

  • function: Dynamic allocation of memory

  • Note: SIZE is only the data type stored in the application for memory, so it is recommended to give it to the following ways when programming the data type stored in the memory block. "Length * SIZEOF (Data Type) ";


void * Calloc (size_t nmenb, size_t size);

Calloc ) The function is allocated in the NMEMB element, wherein each element is a SIZE byte. This function returns a pointer if the required space is invalid. After allocating memory, the calloc () function is initialized by setting all bits to 0. For example, call the calloc () function to allocate storage space for N integers, and ensure that all integers are initialized to 0:

pi = Calloc (n, sizeof (int));

Because the calloc () function will clear allocated memory, the malloc () function is not, so you can call the "1" as the first argument, which assigns space for any type of data item. For example:

struct point {int x, y;} * pi;

pi = calloc (1, sizeof (struct point));

After this statement, Pi will point to a structure, and members x and y of this structure are set to 0.

Usually use free (initiated address pointer) to release memory, otherwise, memory applications will affect the performance of the computer, so that the computer is restarted. If you don't get it after use, you can also use this nature to access the block memory.

Header file: stdlib.h or malloc.h

related functions: Malloc, Realloc, Free_Alloca

Application example

program Example 1

 #define_crt_secure_no_warnings # include main () {char * str = null; / * Assign memory space * / Str = (char *) Calloc (10, sizeof (char)) ; / * Write Hello * / STRCPY (STR, "Hello"); / * Display Variable Content * / Printf ("String IS% S \ N", STR); / * Release Space * / Free (STR); RETURN 0;} 

Sample 2

From this example, it can be seen that the element is initialized after the storage space is completed.

 # include # includeint main () {INT i; int * Pn = (int *) Calloc (10, sizeof (int)); for (i = 0; i 

​​output ten 0

Related Articles