【发布时间】:2011-02-06 00:32:15
【问题描述】:
我感兴趣地阅读了C difference between malloc and calloc 的帖子。我在我的代码中使用了 malloc,想知道使用 calloc 会有什么不同。
我现在使用 malloc 的(伪)代码:
场景 1
int main()
{
allocate large arrays with malloc
INITIALIZE ALL ARRAY ELEMENTS TO ZERO
for loop //say 1000 times
do something and write results to arrays
end for loop
FREE ARRAYS with free command
} //end main
如果我使用 calloc 而不是 malloc,那么我将拥有:
场景2
int main()
{
for loop //say 1000 times
ALLOCATION OF ARRAYS WITH CALLOC
do something and write results to arrays
FREE ARRAYS with free command
end for loop
} //end main
我有三个问题:
如果数组非常大,哪种方案效率更高?
如果数组非常大,哪种方案更省时?
在这两种情况下,我只是写入数组,因为对于 for 循环中的任何给定迭代,我从第一个元素到最后一个元素按顺序写入每个数组。重要的问题:如果我在场景 1 中使用 malloc,那么是否有必要将元素初始化为零?用 malloc 说我有数组 z = [garbage1,garbage2,garbage 3]。对于每次迭代,我按顺序编写元素,即在第一次迭代中我得到 z =[some_result,garbage2,garbage3],在第二次迭代中我在第一次迭代中得到 z =[some_result, another_result,garbage3] 等等on,那么我需要在 malloc 之后专门初始化我的数组吗?
【问题讨论】:
-
是的,这就是为什么我提到我阅读了另一篇文章。我想在这里更具体一点。
-
您自己测量过吗?你的机器上的结果是什么?
-
还没有。如果有差异我会回来写的。
-
这是一个相关(稍后)的问题,它探讨了为什么 calloc 可以比 malloc+memset 快得多(10 倍)。 stackoverflow.com/questions/2688466
标签: c optimization malloc calloc