区别是什么:

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

And:

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

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


当前回答

一个不太为人所知的区别是,在具有乐观内存分配的操作系统(如Linux)中,由malloc返回的指针直到程序实际接触它时才得到实际内存的支持。

calloc确实会接触内存(它会在内存上写0),因此您可以确定操作系统正在用实际的RAM(或swap)支持分配。这也是为什么它比malloc慢的原因(它不仅必须将它归零,操作系统还必须通过交换其他进程来找到合适的内存区域)

例如,请参阅这个SO问题以进一步讨论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/

一个不太为人所知的区别是,在具有乐观内存分配的操作系统(如Linux)中,由malloc返回的指针直到程序实际接触它时才得到实际内存的支持。

calloc确实会接触内存(它会在内存上写0),因此您可以确定操作系统正在用实际的RAM(或swap)支持分配。这也是为什么它比malloc慢的原因(它不仅必须将它归零,操作系统还必须通过交换其他进程来找到合适的内存区域)

例如,请参阅这个SO问题以进一步讨论malloc的行为

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

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

摘自Georg Hager的博客上的一篇文章,用calloc()进行有趣的基准测试

When allocating memory using calloc(), the amount of memory requested is not allocated right away. Instead, all pages that belong to the memory block are connected to a single page containing all zeroes by some MMU magic (links below). If such pages are only read (which was true for arrays b, c and d in the original version of the benchmark), the data is provided from the single zero page, which – of course – fits into cache. So much for memory-bound loop kernels. If a page gets written to (no matter how), a fault occurs, the “real” page is mapped and the zero page is copied to memory. This is called copy-on-write, a well-known optimization approach (that I even have taught multiple times in my C++ lectures). After that, the zero-read trick does not work any more for that page and this is why performance was so much lower after inserting the – supposedly redundant – init loop.

区别1:

Malloc()通常分配内存块,它是初始化的内存段。

Calloc()分配内存块并将所有内存块初始化为0。

区别2:

如果考虑malloc()语法,它只需要1个参数。考虑下面的例子:

data_type ptr = (cast_type *)malloc( sizeof(data_type)*no_of_blocks );

例如:如果你想为int类型分配10块内存,

int *ptr = (int *) malloc(sizeof(int) * 10 );

如果考虑calloc()语法,它将接受2个参数。考虑下面的例子:

data_type ptr = (cast_type *)calloc(no_of_blocks, (sizeof(data_type)));

例如:如果你想为int类型分配10块内存,并将所有这些初始化为0,

int *ptr = (int *) calloc(10, (sizeof(int)));

相似度:

malloc()和calloc()如果没有进行类型强制转换,默认情况下都会返回void* !