Differences between `malloc` and `new`

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


  • 它看起来不错,但你可以强调的事实,你不应该混mallocdeletenewfree

    链接地址: http://www.djcxy.com/p/13772.html

    上一篇: 为什么我应该避免在c ++中使用malloc?

    下一篇: `malloc`和`new`之间的区别