乐闻世界logo
搜索文章和话题

What is the difference between new/delete and malloc/ free ?

1个答案

1

In C++ programming, new/delete and malloc/free are both tools for dynamic memory allocation and deallocation, but they have several key differences:

1. Constructors and Destructors

new/delete:

  • new calls the object's constructor during memory allocation, meaning it not only allocates memory but also initializes the object.
  • delete calls the object's destructor before deallocating memory, ensuring proper cleanup.

For example, consider a class Person that defines a constructor and destructor. new automatically invokes the constructor, and delete automatically invokes the destructor:

cpp
class Person { public: Person() { cout << "Constructor called" << endl; } ~Person() { cout << "Destructor called" << endl; } }; Person *p = new Person(); // automatically invokes the constructor delete p; // automatically invokes the destructor

malloc/free:

  • malloc allocates a block of memory of the specified size without invoking the constructor.
  • free deallocates memory without invoking the destructor.
cpp
Person *p = (Person*)malloc(sizeof(Person)); // does not invoke the constructor free(p); // does not invoke the destructor

2. Type Safety

  • new is type-safe, as it directly returns the correct pointer type without requiring explicit type conversion.
  • malloc returns a void*, which requires explicit type conversion to the specific pointer type.
cpp
Person *p = new Person(); // returns a Person* type Person *q = (Person*)malloc(sizeof(Person)); // requires explicit type conversion

3. Error Handling

  • new throws an exception (std::bad_alloc) when memory allocation fails, which can be caught and handled using exception handling mechanisms.
  • malloc returns NULL when allocation fails, requiring explicit checking of the return value to handle errors.
cpp
try { Person *p = new Person(); } catch (std::bad_alloc &e) { cout << "Memory allocation failed: " << e.what() << endl; } Person *q = (Person*)malloc(sizeof(Person)); if (!q) { cout << "Memory allocation failed" << endl; }

4. Allocation Method and Efficiency

  • new may incur additional overhead compared to malloc due to the invocation of the constructor.
  • malloc may be faster in certain scenarios as it only allocates memory without constructor calls.

In summary, new/delete provides higher-level features such as automatic constructor/destructor invocation, type safety, and exception handling, while malloc/free offers basic memory allocation/deallocation functionality requiring more manual control and error checking. In C++, new/delete is generally preferred because they align better with C++'s object-oriented paradigms.

2024年6月29日 12:07 回复

你的答案