Following are the differences between malloc() and operator new.:
- 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.
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
|calls constructor||does not calls constructors|
|It is an operator||It is a function|
|Returns exact data type||Returns void *|
|on failure, Throws||On failure, returns NULL|
|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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- new vs malloc() and free() vs delete in C++
- new vs operator new in C++
- Difference Between malloc() and calloc() with Examples
- Function Interposition in C with an example of user defined malloc()
- Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
- what happens when you don't free memory after using malloc()
- Placement new operator in C++
- new and delete operators in C++ for dynamic memory
- C++ | new and delete | Question 2
- C++ | new and delete | Question 3
- C++ | new and delete | Question 4
- C++ | new and delete | Question 5
- Overloading New and Delete operator in c++
- C++17 new feature : If Else and Switch Statements with initializers
- C++ 17 | New ways to Assign values to Variables
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- What happens if we mix new and free in C++?
- If memory allocation using new is failed in C++ then how it should be handled?