malloc和calloc区别

calloc(m, n) 本质上等价于
    p = malloc(m * n);
    memset(p, 0, m * n);

填充的零是全零, 因此不能确保生成有用的空指针值或浮点零值

free() 可以安全地用来释放 calloc() 分配的内存。

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。(别人翻译的)
 
2007-08-04 15:34:37

猜你喜欢

转载自blog.csdn.net/big_kevin/article/details/51191728
今日推荐