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.
// Initialization with new()
cout << *n;
- operator vs function: new is an operator, while malloc() is a function.
- return type: new returns exact data type, while malloc() returns void *.
- Failure Condition: On failure, malloc() returns NULL where as new throws bad_alloc exception.
- Memory: In case of new, memory is allocated from free store where as in malloc() memory allocation is done from heap.
- Overriding: We are allowed to override new operator where as we can not override the malloc() function legally.
- Size: Required size of memory is calculated by compiler for new, where as we have to manually calculate size for malloc().
- Buffer Size: malloc() allows to change the size of buffer using realloc() while new doesn’t
|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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- what happens when you don't free memory after using malloc()
- new vs malloc() and free() vs delete 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()
- Difference between Identifiers and Variables in C
- Difference between C and Objective C
- Strict Aliasing Rule in C with Examples
- Difference between cout and puts() in C++ with Examples
- Difference between forward list and list in C++
- Short-Circuiting in C++ and Linux
- Different types of range-based for loop iterators in C++
- Learn C++ Programming Step by Step - A 20 Day Curriculum!
- Difference between C and Dart
Improved By : Yash Kumar Atri