What is the difference between new and malloc in C++?
| Point | new / delete | malloc / free |
|---|---|---|
| Language | C++ | C (also usable in C++) |
| Constructor | Called | Not called |
| Return type | The correct pointer type | void* (needs a cast) |
| On failure | Throws std::bad_alloc | Returns NULL |
| Size | Calculated by the compiler | You give the bytes |
#include <iostream>
struct Item {
Item() { std::cout << "constructed\n"; }
~Item() { std::cout << "destroyed\n"; }
};
int main() {
Item* p = new Item; // allocates and constructs
delete p; // destroys and frees
}
Output
constructed
destroyed
In modern C++ do not write them by hand. Use std::make_unique and containers. See Dynamic Memory and Smart Pointers.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |