What is the difference between new and malloc?

Here are the differences between new and malloc,

  1. Operator new constructs an object (calls constructor of object), malloc does not. Hence new invokes the constructor (and delete invokes the destructor)This is the most important difference.
  2. operator new is an operator, malloc is a function.
  3. operator new can be overloaded, malloc cannot be overloaded.
  4. operator new throws an exception if there is not enough memory, malloc returns a NULL.
  5. operator new[] requires you to specify the number of objects to allocate, malloc requires you to specify the total number of bytes to allocate.
  6. operator new/new[] must be matched with operator delete/delete[] to deallocate memory, malloc() must be matched with free() to deallocate memory.

Syntax of new is:
p_var = new type name;
Where p_var is a previously declared pointer of type typename. And typename can be any basic data type.

Example:
int  *p;
p = new int;
It allocates memory space for an integer variable.

Syntax of malloc is:
p_var = (typename *)malloc(sizeof(typename));
Where p_var is a previously declared pointer of type typename. And typename can be any basic data type.

Example:
int *p;
p = (int *)malloc(sizeof(int));
This statement “allocates” or “reserves” a block of memory for an integer from the heap. Then it places the address of the reserved block into the pointer variable (p, in this case).

Chitra
Chitra

4 thoughts on “What is the difference between new and malloc?

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in