C++ has several functions to acquire dynamic storage, most of which differ in some fundamental way. Several more are usually added by the OS.
Two of these are of special interest due to their portability and similarity: malloc
and ::operator new
.
Are there any differences (w.r.t. the standard and implementation) between the global void* operator new(size_t, ::std::nothrow&)
and void* malloc(size_t)
?
Since there seems to be some confusion what I am talking about, consider the following two calls:
void* p = ::std::malloc(10);
void* q = ::operator new(10, ::std::nothrow);
The obvious and trivial difference is how to deallocate the memory:
::std::free(p);
::operator delete(q);
Note: This question is not a duplicate of e.g. What is the difference between new/delete and malloc/free? since it talks about using the global operator new
that does not actually perform any ctor calls.
There are two differences I can think of:
Which function you must use to deallocate the memory,
operator delete
vs.free()
.A C++ program can legally provide its own version of
::operator new
and that version is guaranteed to be called bynew
expressions. It's not possible to overridemalloc
with your own version.The macroscopic difference I can see without further research is that the throwing variant of the global
::new
operator throwsstd::bad_alloc
if the allocation cannot be done, whereasmalloc
returnsNULL
. But I do believe that most of the differences listed here apply to the global::new
operator, even if the topic is aboutnew
.The main differences, aside from syntax and
free
vs.delete
, are::operator new
;malloc
comes withrealloc
, for whichnew
has no equivalent;new
has the concept of anew_handler
, for which there is nomalloc
equivalent.(Replacing
malloc
opens up a can of worms. It can be done, but not portably, because it requires knowledge of the linker.)