开发者

Regarding the differences between malloc and new in terms of their respective mechanisms of handling memory allocation? [duplicate]

开发者 https://www.devze.com 2023-04-09 08:15 出处:网络
This question already has answers here: What is the difference between new/delete and malloc/free? 开发者_StackOverflow社区(15 answers)
This question already has answers here: What is the difference between new/delete and malloc/free? 开发者_StackOverflow社区 (15 answers) Closed 7 years ago.

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


  • malloc doesn't throw bad_alloc exception as new does.
    • Because malloc doesn't throw exceptions, you have to check its result against NULL (or nullptr in c++11 and above), which isn't necessary with new. However, new can be used in a way it won't throw expections, as when function set_new_handler is set
  • malloc and free do not call object constructors and destructors, since there is no objects in C.
  • see this question and this post.


Well, malloc() is a more low-level primitive. It just gives you a pointer to n bytes of heap memory. The C++ new operator is more "intelligent" in that it "knows" about the type of the object(s) being allocated, and can do stuff like call constructors to make sure the newly allocated objects are all properly initialized.

Implementations of new often end up calling malloc() to get the raw memory, then do things on top of that memory to initalize the objecs(s) being constructed.


Do you mean how they are implemented?

They can be implemented as anything, just malloc may not call new, and all standard news must call the global operator new(void*). Often new is even implemented as calling malloc but there is no requirement on how that is implemented. There are even dozens of allocators out there, each with some strengths and some weeknesses.

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

  • new throws (unless it is called with std::nothrow) on allocation error. new expressions (not the operator new) calls the ctor.
  • malloc returns 0 on allocation failures.


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

For malloc, the caller has to specify the amount of memory to be allocated, while new automatically determines it.

These differences are concerning allocation, there are tons of others - new will call constructor, new can be overloaded, new is an operator whereas malloc is a function...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号