What is the difference between new/delete and malloc/free?

前端 未结 15 2710
春和景丽
春和景丽 2020-11-21 23:53

What is the difference between new/delete and malloc/free?

Related (duplicate?): In what cases do I use malloc vs

相关标签:
15条回答
  • 2020-11-22 00:20
    • new is an operator, whereas malloc() is a fucntion.
    • new returns exact data type, while malloc() returns void * (pointer of type void).
    • malloc(), memory is not initialized and default value is garbage, whereas in case of new, memory is initialized with default value, like with 'zero (0)' in case on int.
    • delete and free() both can be used for 'NULL' pointers.
    0 讨论(0)
  • 2020-11-22 00:22

    This code for use of delete keyword or free function. But when create a pointer object using 'malloc' or 'new' and deallocate object memory using delete even that object pointer can be call function in the class. After that use free instead of delete then also it works after free statement , but when use both then only pointer object can't call to function in class.. the code is as follows :

    #include<iostream>
    
    
    using namespace std;
    
    class ABC{
    public: ABC(){
        cout<<"Hello"<<endl;
      }
    
      void disp(){
        cout<<"Hi\n";
      }
    
    };
    
    int main(){
    
    ABC* b=(ABC*)malloc(sizeof(ABC));
    int* q = new int[20];
    ABC *a=new ABC();
    b->disp();
    
    cout<<b<<endl;
    free(b);
    delete b;
    //a=NULL;
    b->disp();
    ABC();
    cout<<b;
    return 0;
    }
    

    output :

    Hello
    Hi
    0x2abfef37cc20
    
    0 讨论(0)
  • 2020-11-22 00:24

    In C++ new/delete call the Constructor/Destructor accordingly.

    malloc/free simply allocate memory from the heap. new/delete allocate memory as well.

    0 讨论(0)
提交回复
热议问题