做的有什么区别:
ptr = (char **) malloc (MAXELEMS * sizeof(char *));
Run Code Online (Sandbox Code Playgroud)
要么:
ptr = (char **) calloc (MAXELEMS, sizeof(char*));
Run Code Online (Sandbox Code Playgroud)
什么时候使用calloc而不是malloc是一个好主意,反之亦然?
众所周知,它与初始化分配的内存calloc不同malloc.使用时calloc,内存设置为零.使用时malloc,内存不会被清除.
所以在日常工作中,我认为calloc是malloc+ memset.顺便说一下,为了好玩,我为基准编写了以下代码.
结果令人困惑.
代码1:
#include<stdio.h>
#include<stdlib.h>
#define BLOCK_SIZE 1024*1024*256
int main()
{
int i=0;
char *buf[10];
while(i<10)
{
buf[i] = (char*)calloc(1,BLOCK_SIZE);
i++;
}
}
Run Code Online (Sandbox Code Playgroud)
代码1的输出:
time ./a.out
**real 0m0.287s**
user 0m0.095s
sys 0m0.192s
Run Code Online (Sandbox Code Playgroud)
代码2:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BLOCK_SIZE 1024*1024*256
int main()
{
int i=0;
char *buf[10];
while(i<10)
{
buf[i] = (char*)malloc(BLOCK_SIZE);
memset(buf[i],'\0',BLOCK_SIZE);
i++;
}
}
Run Code Online (Sandbox Code Playgroud)
代码2的输出:
time ./a.out
**real 0m2.693s**
user 0m0.973s
sys 0m1.721s
Run Code Online (Sandbox Code Playgroud)
更换 …
我饶有兴趣地阅读了malloc和calloc之间的后C差异.我在我的代码中使用了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
Run Code Online (Sandbox Code Playgroud)
如果我使用calloc而不是malloc,那么我将:
Scenario2
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
Run Code Online (Sandbox Code Playgroud)
我有三个问题:
如果阵列非常大,哪个场景更有效?
如果阵列非常大,哪个场景会更有时间效率? …