优先选择 malloc 而不是 calloc
可能的重复:
malloc 和 calloc 之间的区别
是否存在您更喜欢 malloc 的情况卡洛克。我知道 malloc 和 calloc 都动态分配内存,并且 calloc 还将分配的内存中的所有位初始化为零。 由此我猜想使用 calloc 总是比 malloc 更好。或者在某些情况下 malloc 更好?性能可能是?
Possible Duplicate:
c difference between malloc and calloc
Is there any situation where you would prefer malloc over calloc. i know both malloc and calloc allocate memory dynamically and that calloc also initializes all bits in alloted memory to zero.
From this i would guess its always better to use calloc over malloc. Or is there some situations where malloc is better? Performance may be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常,您分配内存的具体目的是在那里存储某些内容。这意味着(至少大部分)由 calloc 初始化为零的空间很快就会被其他值覆盖。因此,大多数代码使用
malloc
来提高一点速度,而不会造成真正的损失。我见过的 calloc 的唯一用途几乎是(据说)对 Java 相对于 C++ 的速度进行基准测试的代码。在 C++ 版本中,它使用 calloc 分配了一些内存,然后使用 memset 再次初始化内存(在我看来)这是一种相当透明的尝试,以产生有利于结果的结果爪哇。
You're normally allocating memory with the specific intent of storing something there. That means (at least most of) the space that's zero-initialized by
calloc
will soon be overwritten with other values. As such, most code usesmalloc
for a bit of extra speed with no real loss.Nearly the only use I've seen for
calloc
was code that was (supposedly) benchmarking the speed of Java relative to C++. In the C++ version, it allocated some memory withcalloc
, then usedmemset
to initialize the memory again in (what seemed to me) a fairly transparent attempt at producing results that favored Java.如果您需要对动态分配的内存进行零初始化,请使用
calloc
。如果不需要将动态分配的内存进行零初始化,则使用
malloc
。您并不总是需要零初始化的内存;如果不需要内存零初始化,则无需支付初始化成本。例如,如果您分配内存,然后立即复制数据以填充分配的内存,则没有任何理由执行零初始化。
calloc
和malloc
是执行不同操作的函数:使用最适合您需要完成的任务的函数。If you need the dynamically allocated memory to be zero-initialized then use
calloc
.If you don't need the dynamically allocated memory to be zero-initialized, then use
malloc
.You don't always need zero-initialized memory; if you don't need the memory zero-initialized, don't pay the cost of initializing it. For example, if you allocate memory and then immediately copy data to fill the allocated memory, there's no reason whatsoever to perform zero-initialization.
calloc
andmalloc
are functions that do different things: use whichever one is most appropriate for the task you need to accomplish.如果您不小心,依赖 calloc 的零初始化可能会很危险。正如预期的那样,清零内存为整型类型提供 0,为 char 类型提供 \0。但它不一定对应于 float/double 0 或 NULL 指针。
Relying on calloc's zero-initialisation can be dangerous if you're not careful. Zeroing memory gives 0 for integral types and \0 for char types as expected. But it doesn't necessarily correspond to float/double 0 or NULL pointers.