Difference Between new vs malloc() and delete vs free() in C++

Master C++ with Real-time Projects and Kickstart Your Career Start Now!!

Program 1

// Program for difference between new and malloc() , delete free()
#include<iostream>
#define clrscr() system("cls")
using namespace std;
class Test
{
    public:
    Test()
    {
        cout<<"\nHello I am constructor of class Test\n";
    }
    ~Test()
    {
        cout<<"\nHello I am destructor of class Test\n";
    }
};

// class MyClass
// {
//     public:
//     MyClass()
//     {
//         cout<<"\nHello I am constructor of class Myclass\n";
//     }
//     ~MyClass()
//     {
//         cout<<"\nHello I am destructor of class Myclass\n";
//     }
// };

int main()
{
    clrscr();
    Test *T=new Test;   // using new
    cout<<"\nDynamic memory using new operator";
    delete T; // using delete
    cout<<"\nDynamic memory remove using  delete operator";

  Test *T1=(Test*)malloc(sizeof (Test));
   cout<<"\nDynamic memory using malloc function";
   free(T1);
   cout<<"\nDynamic memory  remove using free function";
}

 

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *