What is the difference between new
/delete
and malloc
/free
?
Related (duplicate?): In what cases do I use malloc vs
new
/delete
is C++, malloc
/free
comes from good old C.
In C++, new
calls an objects constructor and delete
calls the destructor.
malloc
and free
, coming from the dark ages before OO, only allocate and free the memory, without executing any code of the object.
new
calls the ctor of the object, delete
call the dtor.
malloc
& free
just allocate and release raw memory.
new
and delete
are C++ primitives which declare a new instance of a class or delete it (thus invoking the destructor of the class for the instance).
malloc
and free
are C functions and they allocate and free memory blocks (in size).
Both use the heap to make the allocation. malloc
and free
are nonetheless more "low level" as they just reserve a chunk of memory space which will probably be associated with a pointer. No structures are created around that memory (unless you consider a C array to be a structure).
Table comparison of the features:
Feature | new/delete | malloc/free
--------------------------+--------------------------------+-------------------------------
Memory allocated from | 'Free Store' | 'Heap'
Returns | Fully typed pointer | void*
On failure | Throws (never returns NULL) | Returns NULL
Required size | Calculated by compiler | Must be specified in bytes
Handling arrays | Has an explicit version | Requires manual calculations
Reallocating | Not handled intuitively | Simple (no copy constructor)
Call of reverse | Implementation defined | No
Low memory cases | Can add a new memory allocator | Not handled by user code
Overridable | Yes | No
Use of (con-)/destructor | Yes | No
Technically memory allocated by new comes from the 'Free Store' while memory allocated by malloc comes from the 'Heap'. Whether these two areas are the same is an implementation detail, which is another reason that malloc and new can not be mixed.
There are a few things which new
does that malloc
doesn’t:
new
constructs the object by calling the constructor of that objectnew
doesn’t require typecasting of allocated memory.So, if you use malloc
, then you need to do above things explicitly, which is not always practical. Additionally, new
can be overloaded but malloc
can’t be.
In a word, if you use C++, try to use new
as much as possible.
1.new syntex is simpler than malloc()
2.new/delete is a operator where malloc()/free() is a function.
3.new/delete execute faster than malloc()/free() because new assemly code directly pasted by the compiler.
4.we can change new/delete meaning in program with the help of operator overlading.