开发者

Differences between `malloc` and `new` [duplicate]

This question already has answers here: Closed 12 years ago.

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:

  1. placement new
  2. delete[]
  3. _set_new_handler() function


I would like to add the following with your differences,

  1. 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.

  2. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜