1.malloc() vs new
1) new会调用构造函数,而malloc() 不能。实际上new 也可以用来初始化原始数据类型(char, int, float.. 等)。
例如,下面程序会输出10。
#include<iostream>
using namespace std;
int main()
{
int *n = new int(10); //使用new()初始化
cout << *n;
getchar();
return 0;
}
2) new是一个操作符,而malloc()是一个函数。
3) new返回抽象数据类型,而malloc()返回指针void *。
2.free() vs delete
在C++中,delete操作符仅能用于一个使用new操作符分配的内存指针,或者一个NULL指针。而free()仅用于一个使用malloc()分配的内存指针,或者一个NULL指针。
换言之,它们不能混合使用。
#include<stdio.h>
#include<stdlib.h>
int main()
{
int x;
int *ptr1 = &x;
int *ptr2 = (int *)malloc(sizeof(int));
int *ptr3 = new int;
int *ptr4 = NULL;
delete ptr1; //非法使用delete, 因为ptr1所指向的内存分配在栈上
delete ptr2; //非法使用delete, 因为ptr2所指向的内存使用malloc()分配,而不是new
//下面两个是正确使用delete的case
delete ptr3;
delete ptr4;
return 0;
}
编译可以通过。但运行的时候会发生异常。