Skip to content
Related Articles

Related Articles

Improve Article
malloc() vs new
  • Difficulty Level : Easy
  • Last Updated : 13 Oct, 2020

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.

CPP




#include<iostream>
using namespace std;
int main()
{
    // Initialization with new()
    int *n = new int(10);
    cout << *n;
    getchar();
    return 0;
}
Output: 
10


 

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 bad_alloc exception.



5. Memory: In case of new, memory is allocated from free store where as in malloc() memory allocation is done from heap.

6. Size: Required size of memory is calculated by compiler for new, where as we have to manually calculate size for malloc().

7. Buffer Size: malloc() allows to change the size of buffer using realloc() while new doesn’t

newmalloc
calls constructordoes not calls constructors
It is an operatorIt is a function
Returns exact data typeReturns void *
on failure, ThrowsOn failure, returns NULL
size is calculated by compilersize 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.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :