1. malloc和calloc的差别
函数名 | 返回值 | 参数 | 参数与返回地址的关系 | 结果一样只不过calloc用起来更方便些 | 其他差别 |
calloc | 地址 | (int num, int size) | =num*size | =4*8 = 32 | 对内存初始化为0 |
malloc | (int num) | =num | =32 | 不初始化 |
2. 用 malloc实现calloc的源码
#include "ansidecl.h"
#include <stddef.h>
/* For systems with larger pointers than ints, this must be declared. */
PTR malloc (size_t);
void bzero (PTR, size_t);
PTR
calloc (size_t nelem, size_t elsize)
{
register PTR ptr;
if (nelem == 0 || elsize == 0)
nelem = elsize = 1;
ptr = malloc (nelem * elsize);
if (ptr) bzero (ptr, nelem * elsize);
return ptr;
}