区别是什么:

ptr = malloc(MAXELEMS * sizeof(char *));

And:

ptr = calloc(MAXELEMS, sizeof(char*));

什么时候使用calloc优于malloc或反之亦然?


当前回答

The documentation makes the calloc look like malloc, which just does zero-initialize the memory; this is not the primary difference! The idea of calloc is to abstract copy-on-write semantics for memory allocation. When you allocate memory with calloc it all maps to same physical page which is initialized to zero. When any of the pages of the allocated memory is written into a physical page is allocated. This is often used to make HUGE hash tables, for example since the parts of hash which are empty aren't backed by any extra memory (pages); they happily point to the single zero-initialized page, which can be even shared between processes.

任何对虚拟地址的写都被映射到一个页,如果该页是零页,则分配另一个物理页,将零页复制到那里,并将控制流返回给客户端进程。这与内存映射文件、虚拟内存等工作方式相同。它使用分页。

下面是一个关于这个主题的优化故事: http://blogs.fau.de/hager/2007/05/08/benchmarking-fun-with-calloc-and-zero-pages/

其他回答

Calloc一般是malloc+memset为0

显式使用malloc+memset通常会稍微好一点,特别是当你在做以下事情时:

ptr=malloc(sizeof(Item));
memset(ptr, 0, sizeof(Item));

That is better because sizeof(Item) is know to the compiler at compile time and the compiler will in most cases replace it with the best possible instructions to zero memory. On the other hand if memset is happening in calloc, the parameter size of the allocation is not compiled in in the calloc code and real memset is often called, which would typically contain code to do byte-by-byte fill up until long boundary, than cycle to fill up memory in sizeof(long) chunks and finally byte-by-byte fill up of the remaining space. Even if the allocator is smart enough to call some aligned_memset it will still be a generic loop.

一个值得注意的例外是,当您对一个非常大的内存块(一些power__2kb)执行malloc/calloc时,在这种情况下,可以直接从内核进行分配。由于操作系统内核通常会出于安全原因将它们放弃的所有内存归零,足够聪明的calloc可能只返回内存,而不进行额外的归零。同样,如果你只是分配一些你知道很小的东西,那么在性能方面使用malloc+memset可能会更好。

块数: Malloc()分配请求的单个内存块, Calloc()为请求的内存分配多个块

初始化: Malloc() -不清除和初始化分配的内存。 Calloc() -将分配的内存初始化为0。

速度: Malloc()速度很快。 Calloc()比malloc()慢。

参数和语法: Malloc()接受1个参数:

字节 要分配的字节数

Calloc()有两个参数:

长度 要分配的内存块的数量 字节 在每个内存块上分配的字节数

void *malloc(size_t bytes);         
void *calloc(size_t length, size_t bytes);      

内存分配方式: malloc函数从可用堆中分配所需“大小”的内存。 calloc函数分配的内存大小等于' num *size '。

名称含义: malloc的意思是“内存分配”。 calloc的意思是“连续分配”。

在<stdlib.h>标头中声明的calloc()函数比malloc()函数提供了几个优点。

它将内存分配为一定数量的给定大小的元素 它初始化所分配的内存,这样所有的位都是 零。

malloc和calloc都分配内存,但calloc将所有位初始化为0,而malloc则不这样做。

可以说,Calloc相当于malloc + memset + 0(其中memset将指定的内存位设置为0)。

因此,如果不需要初始化为0,那么使用malloc可能会更快。

calloc的一个经常被忽视的优点是,它将帮助保护您免受整数溢出漏洞的侵害。比较:

size_t count = get_int32(file);
struct foo *bar = malloc(count * sizeof *bar);

vs.

size_t count = get_int32(file);
struct foo *bar = calloc(count, sizeof *bar);

如果count大于SIZE_MAX/sizeof *bar,前者可能导致少量分配和后续缓冲区溢出。在这种情况下,后者将自动失败,因为无法创建如此大的对象。

当然,您可能不得不注意不符合规范的实现,这些实现简单地忽略了溢出的可能性……如果在您的目标平台上存在这个问题,那么无论如何都必须对溢出进行手动测试。