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.
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 setmalloc
and free
do not call object constructors and destructors, since there is no objects in C
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With