Kus*_*ari 3 c dynamic-memory-allocation
任何人都可以解释在C中使用malloc()和calloc()动态内存分配之间的区别是什么?
尝试这样做:使用malloc分配一些内存
char* pszKuchBhi ;
pszKuchBhi = malloc(10) ;
printf( "%s\n", pszKuchBhi ) ;
// Will give some junk values as the memory allocated is not initialized and
// was storing some garbage values
Run Code Online (Sandbox Code Playgroud)
现在用calloc替换malloc同样做.看到不同.
char* pszKuchBhi ;
pszKuchBhi = calloc( 10, 1 ) ;
printf( "%s\n", pszKuchBhi ) ;
//Will print nothing as the memory is initialized to 0
Run Code Online (Sandbox Code Playgroud)
calloc分配的内存初始化为0.初学者初始化内存很好,但性能方面的calloc很慢,因为它必须分配然后初始化.为了更好地澄清,你可以随时谷歌相同的问题,但更好地体验它来看看里面.你也可以留意你的记忆,亲眼看看.