malloc()和calloc()的区别2006-10-17 11:37:00
【评论】
【打印】
【字体:大 中 小】
本文链接:http://blog.pfan.cn/wenzhuo316/19413.html
Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slightly different from the other. malloc() takes a size and returns a pointer to a chunk of memory at least that big:
void *malloc( size_t size );
malloc()和calloc()都是用来分配动态内存的函数,两者的操作有以下的区别:
malloc()以分配的内存大小size为参数返回一个指针,该指针指向一块最小值为size的内存区域。
calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk of memory
at least big enough to hold them all:void *calloc( size_t numElements, size_t sizeOfElement );
calloc的参数为一组元素和每个元素的size,返回的指针指向的内存至少可以存储所有的这些元素单元。
There are one major difference and one minor difference between the two functions. The major difference is that malloc() doesn't initialize the allocated memory. The first time malloc() gives you a particular chunk of memory, the memory might be full of zeros. If memory has been allocated, freed, and reallocated, it probably has whatever junk was left in it. That means, unfortunately, that a program might run in simple cases (when memory is never reallocated) but break when used harder (and when memory is reused). calloc() fills the allocated memory with all zero bits. That means that anything there you are going to use as a char or an int of any length, signed or unsigned, is guaranteed to be zero. Anything you are going to use as a pointer is set to all zero bits. That is usually a null pointer, but it is not guaranteed.Anything you are going to use as a float or double is set to all zero bits; that is a floating-point zero on some types of machines, but not on all.
两者间有一个主要和次要的区别。主要区别为malloc不初始化分配的内存区域。第一次调用malloc返回的内存可能初值为0,如果该内存被分配、释放然后又重新分配,那么存储区可能存储的就是残留的垃圾数据。也就是说,程序可能在内存不重新分配的简单情况下可以运行,不幸的是如果内存可以重分配,程序就会异常。calloc会初始化分配的内存为0,即你将使用的任何东西,不管是字符还是任何长度,有符号或无符号的整数都是0。你的指针也都指向为0的字节位。通常是一个空指针,但并不保证总是这样。浮点数和双精度型的数据也都是0,有的机器上有值为0的浮点数指针,但不普遍。
The minor difference between the two is that calloc() returns an array of objects; malloc() returns one object. Some people use calloc() to make clear that they want an array.
两者次要的区别为calloc返回一串对象,malloc返回一个对象,当强调想返回一个队列时,应该调用calloc。
说明:翻译为我自己做的,若有异议,欢迎讨论。
阅读(7040) | 评论(2)
版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!
评论