1、先看看它们的原型(stdlib.h):
void *malloc( size_t size );
void *calloc( size_t numElements, size_t sizeOfElement );
void* realloc(void* ptr, unsigned newsize);
2、共同之处:
它们的返回值都是请求系统分配的地址,如果请求失败就返回NULL。
调用free释放(C++中用new/delete)。
3、不同之处:
malloc用于申请一段新的地址,参数size为需要内存空间的长度,如:
char* p;
p=(char*)malloc(20);
calloc与malloc相似,参数sizeOfElement为申请地址的单位元素长度,numElements为元素个数,如:
char* p;
p=(char*)calloc(20,sizeof(char));
realloc是给一个已经分配了地址的指针重新分配空间,参数ptr为原有的空间地址,newsize是重新申请的地址长度,如:
char* p;
p=(char*)malloc(sizeof(char)*20);
p=(char*)realloc(p,sizeof(char)*40);
4、