Differences between `malloc` and `new` [duplicate]
Possible Duplicate:
What is the difference between new/delete and malloc/free?
Could someone please revise/edit the below - the differences between malloc and new - and see if everything is correct, or am I missing something or got something wrong? Thank you,
Both malloc
and new
are used for Dynamic Memory Allocation.
malloc
is a C function, whereas new
is a C++ operator.
malloc
requires a special typecasting when it allocates memory dynamically,
whereas new
does not require any typecasting.
Whenever we use new
for allocating memory, it also invokes any required constructors, whereas malloc
doesn't do that.
malloc
can fail and returns a NULL
pointer if memory is exhausted, whereas new
never returns a NULL pointer, but indicates failure by throwing an exception instead.
While using malloc
, free
is the C functio开发者_如何学Cn used to free up the allocated memory.
While using new
, delete
is the C++ operator used to free up the allocated memory AND call any required destructors.
Important things to note and remember:
placement new
delete[]
_set_new_handler()
function
I would like to add the following with your differences,
malloc" does is allocate memory and return a pointer to it. For whatever reason, the designers of the C language implemented it as a standard library function. On the Other hand "new" is to instantiate an object, by allocating memory and calling the appropriate constructors. Seems reasonable to me that this function is far more tied to the language than something that simply allocates storage.
new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new.
It looks ok, but you could stress the fact that you should never mix malloc
with delete
and new
with free
.
Don't forget new[]
and delete[]
, for array allocation and deallocation respectively.
精彩评论