C++ malloc() vs new
malloc() vs new
On this page we will discuss about difference between malloc() and operator new in C++.
In C++, malloc() is a function from the C standard library for dynamically allocating memory. It is used to allocate a block of memory on the heap.
In C++, the new operator is used to dynamically allocate memory and construct an object in that memory.
In C++, malloc() and new are similar in that they both dynamically allocate memory on the heap, but new also constructs an object in that memory and has additional functionality.
Here we will discuss the key difference between malloc() and operator new.
Key differences between malloc() and new in C++
malloc() | new |
---|---|
It is a function from the C standard library. | It is a C++ operator. |
It only allocates memory. | It allocates memory and calls the constructor of the object being created. |
It returns a pointer to the first byte of the allocated memory. | It returns a pointer to the newly constructed object. |
Memory allocated with malloc() must be explicitly freed using the free() function. | Memory allocated with new is automatically freed when the program exits. |
It returns void *. | It returns exact data type. |
It does not perform type checking. | It checks for type correctness and throws an exception if the allocation fails. |
It does not call constructors. | It calls constructors. |
malloc() cannot be overloaded. | Operator new can be overloaded. |
It can be used to allocate aligned memory. | It cannot be used to allocate aligned memory. |
Example of malloc()
#include <iostream> using namespace std; int main() { int *p = (int *)malloc(sizeof(int)); // Allocate memory for an integer if (p == NULL) { cout << "Memory allocation failed\n"; return 1; } *p = 5; // Assign a value to the memory cout << "The value of the integer is: " << *p << endl; free(p); // Free the allocated memory return 0; }
Output:
The value of the integer is: 5
Example of new
#include <iostream> using namespace std; class Test { public: Test(int x) { value = x; cout << "Test object created with value " << value << endl; } ~Test() { cout << "Test object destroyed with value " << value << endl; } int getValue() { return value; } private: int value; }; int main() { Test *p = new Test(5); // Allocate memory for Test object and call constructor cout << "The value of the Test object is: " << p->getValue() << endl; delete p; // Free the allocated memory and call destructor return 0; }
Output:
Test object created with value 5 The value of the Test object is: 5 Test object destroyed with value 5
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment