new vs malloc and delete vs free.
The difference between 'new' & malloc():
- Operator new constructs an object (calls constructor of object), malloc does not.
When new has an object, memory space for the object is not only allocated but the object's constructor is called.
- Operator new is an operator, malloc is a function.
- Operator new can be overloaded, malloc cannot be overloaded.
- Operator new throws an exception if there is not enough memory, malloc returns a NULL.
- Operator new[] requires to specify the number of objects to allocate, malloc requires to specify the total number of bytes to allocate.
Operator new automatically calculates the size of the object that it constructs. Conversely, with malloc(), the programmer has to specify explicitly the number of bytes that have to be allocated.
- malloc() returns void *, which has to be explicitly cast to the desired type but new returns the proper type.
Operator new returns a pointer to the desired type, so no explicit typecast is required. But, malloc() returns void *, which has to be explicitly cast to the desired type. This is both tedious and dangerous.
- Operator new/new[] must be matched with operator delete/delete[] to deallocate memory, malloc() must be matched with free() to deallocate memory.The new/delete couple does not have a realloc alternative that is available when malloc/free pair is used. realloc is used to resize the length of an array or a memory block dynamically.
The difference between 'delete' & free():
- delete invokes the destructor of the object to be deallocated, free does not do this.
- delete can be overloaded, free cannot.

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home