优先选择 malloc 而不是 calloc

发布于 2024-10-03 16:34:58 字数 331 浏览 6 评论 0原文

可能的重复:
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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

若言繁花未落 2024-10-10 16:34:59

通常,您分配内存的具体目的是在那里存储某些内容。这意味着(至少大部分)由 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 uses malloc 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 with calloc, then used memset to initialize the memory again in (what seemed to me) a fairly transparent attempt at producing results that favored Java.

爱她像谁 2024-10-10 16:34:58

如果您需要对动态分配的内存进行零初始化,请使用calloc

如果不需要将动态分配的内存进行零初始化,则使用malloc

您并不总是需要零初始化的内存;如果不需要内存零初始化,则无需支付初始化成本。例如,如果您分配内存,然后立即复制数据以填充分配的内存,则没有任何理由执行零初始化。

callocmalloc 是执行不同操作的函数:使用最适合您需要完成的任务的函数。

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 and malloc are functions that do different things: use whichever one is most appropriate for the task you need to accomplish.

再浓的妆也掩不了殇 2024-10-10 16:34:58

如果您不小心,依赖 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文