calloc和malloc的区别,兼谈new

来源:互联网 发布:cad mac中文破解版2016 编辑:程序博客网 时间:2024/04/30 07:24
都是动态分配内存。

Both the malloc() and the calloc() s 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 ); //分配的大小


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 ); // 分配元素的个数和每个元素的大小


主要的不同是malloc不初始化分配的内存,calloc初始化已分配的内存为0。calloc等于malloc后在memset.

There are one major difference and one minor difference between the two. The major difference is that malloc() doesnt 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.


次要的不同是calloc返回的是一个数组,而malloc返回的是一个对象

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.


malloc 和 new 

至少有两点不同。

一, new 返回指定类型指针并且自动计算所需要大小比: 

int *p; 
p = new int; //返回类型int* 类型(整数型指针)分配大小 sizeof(int); 
或: 
int* parr; 
parr = new int [100]; //返回类型 int* 类型(整数型指针)分配大小 sizeof(int) * 100; 

而 malloc 则必须由我们计算要字节数并且返回强行转换实际类型指针 
int* p; 
p = (int *) malloc (sizeof(int)); 
第一、malloc 函数返回 void * 类型写成:p = malloc (sizeof(int)); 则程序无法通过编译报错:能 void* 赋值给 int * 类型变量所必须通过 (int *) 来强制转换 
第二、函数实参 sizeof(int) 用于指明整型数据需要大小写成:
int* p = (int *) malloc (1); 
代码也能通过编译事实上只分配了1字节大小内存空间当往里头存入整数会有3字节无家归而直接住进邻居家造成结面内存原有数据内容全部被清空。

malloc 也能达到 new [] 效国申请出段连续内存,方法无非指定所需要内存大小 ,比如想分配100int类型空间: 
int* p = (int *) malloc ( sizeof(int) * 100 ); //分配放得下100整数内存空间 
二, 另外有点能直接看出区别:malloc 只管分配内存,并不能对所得内存进行初始化。所以,在得到的一片新内存中,其值是随机的。


除了分配及释放方法样外通过malloc或new得指针其操作上保持致。


当然,如果考虑到c++中类的构造概念,那差别就更大了。
0 0
原创粉丝点击