0%

Difference Between new and malloc in C++

This is one of the most common interview questions. I used to said that new/delete will call constructor and deconstructor, but malloc/free not. However, except this, there are many other differences.

Free Store and Heap

We always say that new allocates memory from the heap. However this is not accurate. Exactly, new allocates memory from Free Store. In Herb Sutter's book "exceptional C++", he clearly pointed out that there is a difference between them1.

The Free Store area is an abstract concept in C++, whenever a memory is allocated through new operator, that memory is in Free Store area. However, the heap is a term in operating system. By default, the global new and delete are implemented by malloc and free. In that way, the Free Store and heap are similar.

Type-safe

The return value of new operator is a pointer of the object with specified type, no need to cast again. However, malloc returns a pointer with void* type, which need to static_cast to our type.

What if allocate memory failed

In the new operator, if we allocate memory failed, it will throw std::bad_alloc exception. That gives us a chance to free some resources or take other measures. However, when malloc fails, it only return NULL. The new will never return nullptr.

no need to specify memory size in new

When we use new to allocate memory, the compiler will calculate the memory block size according to the type automatically. However, in malloc, we need to specify memory size explicitly.

1
2
3
class Point {...};
Point* p1 = new Point;
Point* p2 = static_cast<Point*>(malloc(sizeof(Point)));

new/delete will call constructor/deconstructor

There are three steps when using the new operator to allocate memory2.

  1. Allocate enough storage for the object.
  2. Construct and initialize the object.
  3. Return a prvalue pointer to the constructed object. However, malloc will not do these construction and initialization.

We can override operator new and operator delete

This is pretty flexible in some specific scenarios, like in game. By this way we can manage the allocation and recycling of objects ourselves.