malloc()和calloc() [英] malloc() and calloc()
本文介绍了malloc()和calloc()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以帮我吗?
malloc()和calloc()有什么区别?
Hi, Can any one help me.
what is the difference between malloc() and calloc()?
Explain in deep manner.
推荐答案
malloc
是内存分配的主力军(calloc
本身使用malloc
).
只需查看以下MSDN
页,您可能会发现自己两个函数之间的区别:
malloc [ calloc [ ^ ].
:)
malloc
is the workhorse for memory allocation (calloc
itself usesmalloc
).
You may find yourself the differences between the two functions just having a look at the followingMSDN
pages:
malloc[^], calloc[^].
:)
calloc提供的已分配内存初始化为零,而malloc分配的内存仅包含其之前的所有垃圾.
同样,calloc接受2个参数,一个用于对象数,一个用于对象的大小,而malloc仅接受要分配的字节数.我相信calloc分配的内存可能会比预期的稍大,因为对象可以与任何相关的平台边界对齐.目的是在将项作为数组访问时使用calloc.
希望有帮助,
Charles Keepax
The allocated memory supplied by calloc is zero initialised, whereas that allocated by malloc just contains whatever junk was in their before.
Also calloc takes 2 arguments one for the number of objects and one for the size of an object, whereas malloc takes just the number of bytes to be allocated. I believe memory allocated by calloc can be slightly larger than expected as the objects can be aligned to any relevant platform boundaries. The intention is for calloc to be used if items are to accessed as an array.
Hope that helps,
Charles Keepax
函数void* malloc(size_t size)
用于分配size
个字节.
它返回一个指向已分配块的指针.
函数void* calloc(size_t nelement, size_t elementSize)
分配了足够的内存来存储总共大小为elementSize
的nelement
个元素.您可以使用它来分配已知数量的元素,例如分配10个my_struct
s:
The functionvoid* malloc(size_t size)
is used to allocatesize
number of bytes.
It returns a pointer to the allocated block.
The functionvoid* calloc(size_t nelement, size_t elementSize)
allocates enough memory to store a total ofnelement
elements of sizeelementSize
. You''d use this to allocate a known number of elements, such as allocating 10my_struct
s:
struct my_struct
{
int x;
int y;
}
...
my_struct* = calloc(10, sizeof(my_struct);
此处 [
It''s explained in more detail here[^]
The memory is also initialized when using calloc
.
Hope this helps,
Fredrik
这篇关于malloc()和calloc()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文