perrynzhou

专注于系统组件研发

0%

new/mallc/delete/free的区别

在使用C/C++开发使用,很多对于mallc和new、free和delete搞不清楚的,这里能简单说下区别

  • 1.malloc和free是库函数;new和delete是C++的关键字
  • 2.malloc是以字节来申请堆内存;new是以类型申请堆空间
  • 3.malloc和free是单纯的申请内存和释放内存
  • 4.new和delete分别负责申请内存调用calss的构造函数初始化和调用析构函数释放资源
  • 5.new申请的内存使用free释放,是不会触发调用析构函数的,一般会造成资源泄露

代码示例

  • 代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    #include <new>
    #include <cstdlib>
    #include <iostream>
    using namespace std;
    class T {
    public:
    T(){cout<<"Call T()"<<endl;iv = 100;};
    ~T(){cout<<"Call ~T()"<<endl;}
    int GetIv(){return iv;}
    private:
    int iv;
    };
    void func()
    {
    int *t1 = static_cast<int *>(malloc(sizeof(int)));
    int *t2 = new int(10);//new 可以申请内存同时也可以赋值
    *t1 = 88;//malloc则不行
    cout << "begin :*t1"<<*t1<<",*t2="<<*t2<<endl;
    free(t1);
    delete t2;
    cout << "end :t1"<<t1<<",t2="<<t2<<endl;

    }
    int main(void)
    {
    //func();
    T *t1 = new T();//她会调用构造函数,以类型申请堆空间
    T *t2 = static_cast<T *>(malloc(sizeof(T))); //不会调用构造和析构函数,以字节申请堆空间
    cout<<"t1.iv = "<<t1->GetIv()<<endl;

    delete t2;//触发析构函数,析构函数用于释放资源
    cout<<"t2.iv = "<<t2->GetIv()<<endl;
    free(t1);//如果new申请的空间,用free释放,析构函数是不会调用,会造成资源泄露
    return 0;
    }
  • 运行
1
2
3
4
5
perryn@:/data/source/Cpp/demo:./a.out
Call T()
t1.iv = 100
t2.iv = 0
Call ~T()