What are the differences between malloc and new in terms of their respective mechanisms of handling memory allocation?
-
`malloc` doesn't throw `bad_alloc` exepetion as `new`, as I think – Sep 30 '11 at 14:20
-
`malloc` and `free` do not call object constructors and destructors. – Alan Sep 30 '11 at 14:20
-
Above comments added to a community-wiki answer. – Robᵩ Sep 30 '11 at 14:21
-
http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.4 – Lundin Sep 30 '11 at 14:24
-
Please see http://stackoverflow.com/questions/7443782/does-dynamic-memory-allocation-differ-in-c-and-c-in-popular-implementations/7444032#7444032 – NPE Sep 30 '11 at 14:33
4 Answers
mallocdoesn't throwbad_allocexception asnewdoes.- 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 withnew. However,newcan be used in a way it won't throw expections, as when functionset_new_handleris set
- Because malloc doesn't throw exceptions, you have to check its result against
mallocandfreedo not call object constructors and destructors, since there is no objects inC.- see this question and this post.
-
Also, because malloc doesn't throw exceptions, you have to check its result against NULL, which isn't necessary with new. – Lundin Sep 30 '11 at 14:25
-
Two more points can be added: (1) placement `new` (2) Compatibility of `malloc/realloc`. – iammilind Sep 30 '11 at 14:41
-
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.
- 391,730
- 64
- 469
- 606
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?
newthrows (unless it is called withstd::nothrow) on allocation error. new expressions (not the operator new) calls the ctor.mallocreturns0on allocation failures.
- 15,673
- 5
- 44
- 57
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...
- 253,575
- 64
- 457
- 625