在c++中,申请内存与释放动态内存,用二者都可以,并且存储方式相同,new与malloc申请内存都在堆中,操作系统无法自动回收,
需要对应的delete与free来释放内存。
c语言中需要头文件<stdlib.h>,new/delete是c++运算符。对于类的对象而言,malloc/free 无法满足动态对象的要求。
具体而言有以下几个区别:
1)new能够自动计算需要分配的内存,而malloc需要手工计算字节数。int *p1 = new int [2] , int *p2 = malloc(2*sizeof(int))
2)new 与 delete 直接带具体类型指针,malloc与free 返回void类型指针。
3)new 是类型安全,而malloc 不是。
4)new 一般由两部构成,new 可以重载
5)new将调用构造函数,malloc不能,delete调用析构函数,而free不能
6)malloc/free是函数,库文件<stdlib.h>,new/delete 运算符
#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"A is here!"<<endl;
}
~A()
{
cout<<"A is dead!"<<endl;
}
private:
int i;
};
int main()
{
A * pA = new A;
delete pA;
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void Testfree()
{
char *str = (char*) malloc (100);
ctrcpy(str,"hello");
free(str);
if (str != NULL)
{
strcpy(str,"world");
printf("%s\n",str);
}
}
int main ()
{
Testfree();
return 0;
}