calloc

calloc

在头文件中定义
void * calloc(size_t num,size_t size);

为具有num大小的对象数组分配内存size,并将分配的存储中的所有字节初始化为零。

如果分配成功,则返回一个指向已分配内存块中适用于任何对象类型的最低(第一个)字节的指针。

如果size为零,则行为是实现定义的(可能会返回空指针,或者可能会返回一些可能不用于访问存储的非空指针)。

calloc是线程安全的:它的行为就好像只访问通过其参数可见的内存位​​置,而不是任何静态存储。先前调用free或realloc来释放内存区域的同步 - 调用calloc来分配同一区域或同一区域内存的一部分。在通过解除分配函数访问内存之后和通过calloc访问内存之前,会发生此同步。所有分配和解除分配功能在内存的每个特定区域都有一个总的顺序。(自C11以来)

参数

在一个-对象的数量
尺寸-每个对象的大小

返回值

成功时,将指针返回到新分配的内存的开始位置。返回的指针必须用free()或来解除分配realloc()

失败时,返回一个空指针。

笔记

由于对齐要求,分配的字节数不一定等于num*size

初始化所有位为零并不保证浮点或指针将分别初始化为0.0和空指针值(尽管在所有常见平台上都是如此)。

最初(在C89中),增加了对零大小的支持以适应如下代码。

OBJ *p = calloc(0, sizeof(OBJ) // "zero-length" placeholder ... while(1) { p = realloc(p, c * sizeof(OBJ) // reallocations until size settles ... // code that may change c or break out of loop }

#include <stdio.h> #include <stdlib.h> int main(void) { int *p1 = calloc(4, sizeof(int) // allocate and zero out an array of 4 int int *p2 = calloc(1, sizeof(int[4]) // same, naming the array type directly int *p3 = calloc(4, sizeof *p3 // same, without repeating the type name if(p2) { for(int n=0; n<4; ++n) // print the array printf("p2[%d] == %d\n", n, p2[n] } free(p1 free(p2 free(p3 }

输出:

p2[0] == 0 p2[1] == 0 p2[2] == 0 p2[3] == 0

参考

  • C11标准(ISO / IEC 9899:2011):