What is the difference between new
/delete
and malloc
/free
?
Related (duplicate?): In what cases do I use malloc vs
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.