-1

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.

1

4 Answers 4

1

Important things to note and remember:

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

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.

0

It looks ok, but you could stress the fact that you should never mix malloc with delete and new with free.

0

Don't forget new[] and delete[], for array allocation and deallocation respectively.

Not the answer you're looking for? Browse other questions tagged or ask your own question.