malloc() vs new

Following are the differences between malloc() and operator new.:

  1. Calling Constructors: new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new. For example, below program prints 10.
    using namespace std;
    int main()
       int *n = new int(10); // initialization with new()
       cout << *n;
       return 0;

  2. operator vs function: new is an operator, while malloc() is a function.
  3. return type: new returns exact data type, while malloc() returns void *.
  4. Failure Condition: On failure, malloc() returns NULL where as new Throws.
  5. Memory: In case of new, memory is allocated from free store where as in malloc() memory allocation is done from heap.
  6. Overriding: We are allowed to override new operator where as we can not override the malloc() function legally.
  7. Size: Required size of memory is calculated by compiler for new, where as we have to manually calculate size for malloc().
new malloc
calls constructor doesnot calls constructors
It is an operator It is a function
Returns exact data type Returns void *
on failure, Throws On failure, returns NULL
Memory allocated from free store Memory allocated from heap
can be overridden cannot be overridden
size is calculated by compiler size is calculated manually

Please write comments if you find anything incorrect in the above post, or you want to share more information about the topic discussed above.

This article is attributed to GeeksforGeeks.org



You Might Also Like

leave a comment



load comments

Subscribe to Our Newsletter