new vs malloc and free vs delete explained with simple example

malloc() and free() are the library functions provided by the C which can be used to allocate and deallocate memory at runtime, whereas new and delete are the the operators provided by C++ which can be used to allocate and deallocate memory at runtime.
The basic difference between new and malloc() is that memory allocation using new calls the constructor which initializes the memory. In case of malloc(), returned memory is uninitialized and needs to be initialized explicitly.
Similarly, deallocating memory using delete calls the destructor and hence allowing to do a proper cleanup whereas in case of free(), destructors are not called and hence cleanup needs to be done prior free() call. Let’s look into some more difference between these functions.

Difference Between new/delete vs malloc()/free()

new/deletemalloc()/free()
Memory is allocated from “Free Store”.Memory is allocated from Heap.
Automatic type-casting is done.Explicit type-casting is needed as malloc always returns “void*”.
In case of error, exception is thrown.In case of error, NULL pointer is returned.
Memory size is automatically calculated by the compiler.Memory size needs to be passed explicitly.
Arrays can be handled easily.User has to handle arrays by themselves.
Reallocation needs to be handled by the User.Reallocation can be done easily.
Can be overridden.Can’t override these functions.
Constructor/Destructor is always called.Constructor/Destructor are not called.
Can add a new memory allocator in case of low memory scenario.No specific help in case of low memory scenario.

Example

Let’s look into an example to understand the differences better.

class Base
{
    public:
        int a;
        char b;
        Base (int a, char c);
        ~Base ();
};

Base::Base (int a, char c): a(a), b(c)
{
    std::cout << "Inside Constructor" << std::endl;
}

Base::~Base ()
{
    std::cout << "Inside Destructor " << std::endl;
}

int main ()
{
    std::cout << "Calling New" << std::endl;
    Base* using_new = new Base(4,'n');
    std::cout << "Calling Malloc" << std::endl;
    Base* using_malloc = (Base*) malloc (sizeof (Base));

    std::cout << "Calling Delete" << std::endl;
    delete using_new;
    std::cout << "Calling free" << std::endl;
    free (using_malloc);
}

Let’s analyze the output of the above program.

Calling New
Inside Constructor
Calling Malloc
Calling Delete
Inside Destructor 
Calling free

Important Points

  • new/delete and malloc()/free() mixing is not advisable.
  • Due to backward compatibility malloc()/free() are supported by almost all C++ compilers.

Leave a Reply

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