As for the differences between malloc and new in terms of their respective memory allocation processing mechanisms?

What are the differences between malloc and new in terms of their respective memory allocation processing mechanisms?

+7
source share
4 answers
  • malloc does not throw a bad_alloc exception as new .
    • Since malloc does not throw exceptions, you need to check its result for NULL (or nullptr in C ++ 11 and above), which is not necessary with new . However, new can be used in such a way that it does not generate expectations, since when setting the set_new_handler function
  • malloc and free do not call object constructors or destructors, since there are no objects in C
  • see this question and this post .
+6
source

Well, malloc() is a lower level primitive. It just gives you a pointer to n bytes of heap memory. The C ++ new operator is more "intelligent" because it "knows" about the type of object (s) selected and can do things like call constructors to make sure that newly selected objects have been correctly initialized.

new implementations often end up calling malloc() to get raw memory, and then do things on top of that memory to initialize the constructed objects (s).

+2
source

Do you mean how they are implemented?

They can be implemented as you like, just malloc cannot call new , and all standard new must call global operator new(void*) . Often new is even implemented as a call to malloc , but there is no requirement on how this is implemented. There are even dozens of dispensers out there, each with some strengths and some weeks.

Or do you mean how they differ at the language level?

  • new throws (if it is not called with std::nothrow ) on a posting error. new expressions (and not the new operator) calls ctor.
  • malloc returns 0 for distribution failures.
+2
source

If the call fails, new will throw an exception, while malloc will return NULL .

For malloc caller must indicate the amount of allocated memory, and new automatically determines it.

These differences relate to selection, there are many others - the new one will call the constructor, the new one can be overloaded, new is the operator, while malloc is the function ...

+1
source

All Articles