What is the difference between new
/delete
and malloc
/free
?
Related (duplicate?): In what cases do I use malloc vs
The most relevant difference is that the new
operator allocates memory then calls the constructor, and delete
calls the destructor then deallocates the memory.
The main difference between new and malloc is that new invokes the object's constructor and the corresponding call to delete invokes the object's destructor.
There are other differences:
new
is type-safe, malloc
returns objects of type void*
new
throws an exception on error, malloc
returns NULL
and sets errno
new
is an operator and can be overloaded, malloc
is a function and cannot be overloaded
new[]
, which allocates arrays, is more intuitive and type-safe than malloc
malloc
-derived allocations can be resized via realloc
, new
-derived allocations cannot be resized
malloc
can allocate an N-byte chunk of memory, new
must be asked to allocate an array of, say, char
types
Looking at the differences, a summary is malloc is C-esque, new is C++-esque. Use the one that feels right for your code base.
Although it is legal for new and malloc to be implemented using different memory allocation algorithms, on most systems new is internally implemented using malloc, yielding no system-level difference.
also,
the global new and delete can be overridden, malloc/free cannot.
further more new and delete can be overridden per type.
malloc()
, we need to include <stdlib.h>
or
<alloc.h>
in the program which is not required for new
.new
and delete
can be overloaded but malloc
can not.new
, we can pass the address where we want to
allocate memory but this is not possible in case of malloc
.The only similarities are that malloc
/new
both return a pointer which addresses some memory on the heap, and they both guarantee that once such a block of memory has been returned, it won't be returned again unless you free/delete it first. That is, they both "allocate" memory.
However, new
/delete
perform arbitrary other work in addition, via constructors, destructors and operator overloading. malloc
/free
only ever allocate and free memory.
In fact, new
is sufficiently customisable that it doesn't necessarily return memory from the heap, or even allocate memory at all. However the default new
does.
new and delete are operators in c++; which can be overloaded too. malloc and free are function in c;
malloc returns null ptr when fails while new throws exception.
address returned by malloc need to by type casted again as it returns the (void*)malloc(size) New return the typed pointer.