0%

malloc和alloc

malloc和alloc

在网上找到的转载的英文资料,附上自己的一些理解点击连接

Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slightly different from the other.

malloc和calloc函数都用来分配动态内存,他们之间的差别很小

malloc() takes a size and returns a pointer to a chunk of memory at least that big:

void *malloc( size_t size );

malloc返回至少有申请内存大小的一块内存(可能更大)

calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk of memoryat least big enough to hold them all:

void *calloc( size_t numElements, size_t sizeOfElement );

calloc返回至少有多块内存大小之和的内存(可能更大)

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

他们之间最主要的差别是,malloc不初始化分配的内存,可能内存中充满的是零。如果内存已经被分配、释放或重新分配过,它可能存放着未知的内容。这意味着当这块内存从申请,修改,再到被重新分配,包含未知的内容会导致程序崩溃

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()用0 bits填充分配的内存,所以不需要初始化。通常这是一个空指针,但并不保证一定是。使用float或double类型被置为zero bits,在某些机器上是浮点零,但不保证一定是。

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返回一个对象。