在了解new和malloc的区别之前,我们首先要知道new和malloc的基本用法,malloc/free是C/C++的标准库函数,函数原型如下,而new是C++的运算符。
malloc函数原型void *malloc(size_t_size);
void* free(void * ptr);
动态开辟内存
malloc: int *p =(int*)malloc(sizeof(int))
free(p)
new: int *p = new int;
delete p;
开辟数组
malloc: int * cpp = (int *)malloc(sizeof(int)*10);
free(p);
new: int *cpp = new int[10];
delete[]cpp;