malloc free, new delete 的异同点

相同点:

都可以动态的申请并释放内存

不同点:

1. 用法不同

  <1> malloc 函数为 void* malloc(size_t size), 用于申请一块长度为 size 字节的内存空间. 假如我们希望申请一个长度为 100 的 int 型数组所需的内存空间的话, 我们需要写成这样, malloc(100*sizeof(int)). 同时注意到 malloc 返回的是 void* 的指针, 这就要求我们进行类型转换, int * ptr = (int*) malloc(100*sizeof(int))

  <2> free 函数为 void free(void*) 指针包含其指向的地址以及指向的类型以及长度, 因此只需传进来一个指针变量即可 free

  <3> new 的操作非常简单, 假如需要申请 100 个 int 型数组的空间, int *ptr = new int[100] 即可. new 自带 sizeof, 类型转换和安全检查. 对于非内部结构的数据成员, new 还可以完成初始化工作(执行构造函数)

  <4> delete 在 free 的基础上还支持析构函数

  <5> 若使用 malloc, free 强行为非内部数据成员分配内存, 那么必须显示的为对象执行构造函数和析构函数. 

2. 编译器报错

  <1> malloc, free 是库函数, 不属于编译器的控制范围

  <2> new. delete 是运算符, 编译器会报错 

3. new, delete, malloc, free 必须成对使用

 new, delete 的功能完全覆盖了 malloc, free

 c 只有 malloc, free, 所以这东西仍要使用

原文地址:https://www.cnblogs.com/xinsheng/p/3483348.html