Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 299
user785099 Avatar asked Sep 30 '11 14:09

user785099


2 Answers

  • 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.
like image 76
8 revs, 4 users 40%user586399 Avatar answered Oct 07 '22 15:10

8 revs, 4 users 40%user586399


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.

like image 38
unwind Avatar answered Oct 07 '22 15:10

unwind