Malloc vs New in C++

Malloc vs New: malloc and new operator in programming languages especially C++ is used to allocate space dynamically in memory (Heap). But both of them perform the same task in different ways. Let’s discuss the difference between malloc and new.

Malloc vs New

Malloc

Malloc in C+ is a function which accepts size as an argument. Therefore malloc syntax usually looks like this:

  • malloc returns untyped pointer i.e void*, therefore it needs to be typecaste into other pointer type explicitly.
  • malloc return NULL if the memory allocation fails due to some reason.
  • By using malloc for creating an object for class, the constructor doesn’t gets called.
  • free() function is used to clear memory in heap.
  • Use of free() function doesn’t call the destructor of the class.

New

New in C++ is an operator which is also used to allocate space in heap/free store for object or pointer. The syntax for new written like this.

  • new return strictly typed pointer, hence it doesn’t require type casting.
  • new does’t return NULL if the memory allocation fails, rather it will cause unwanted situations/errors in your program execution.
  • Constructor gets called when we create object pointer using the new operator.
  • delete command clears the memory taken by the pointer.
  • Also, the destructor of the current object is called on using delete command.
  • new operator doesn’t require explicit calculation of size for pointer creation.

Note:

Using delete command on the object/pointer created using malloc and free() function on the object/pointer declared using new opearator is wrong and may cause an error or unwanted situation.

Conclusion

malloc function was introduced in C language and further new operator was introduced in C++. It means that the new operator is more efficient in dynamically allocating space in the heap.

Thats all for basic of new vs malloc. If you have any doubt then comment below.

admin

I am a B.tech IT Student from India. Technology and programming is the most enthusiastic thing for me in this world. I like learning new techniques and use them for real-world application because I feel tech is future. Let's learn and grow TOGETHER.

Leave a Reply

Close Menu
shares