11/29/2009

malloc vs new

Difference between uses of new/malloc & delete/free:

(a) Operator new constructs an object (calls constructor of object), malloc does not.
(b) Operator new is an operator, malloc is a function.
© Operator new can be overloaded, malloc cannot be overloaded.
(d) Operator new throws an exception if there is not enough memory, malloc returns a NULL.
(e) Operator new[] requires to specify the number of objects to allocate, malloc requires to specify the total number of bytes to allocate.
(f) malloc() returns void *, which has to be explicitly cast to the desired type but new returns the proper type.
(g) Operator new/new[] must be matched with operator delete/delete[] to deallocate memory, malloc() must be matched with free() to deallocate memory.
(h) 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.

reference:http://c.ittoolbox.com/groups/technical-functional/cpp-l/malloc-vs-new-1255507

沒有留言: