Articles

malloc vs new in C++

malloc vs new in C++


In this chapter of C++ interview questions, we will learn about:

  • malloc in c++ and malloc syntax
  • new in c++ and new syntax
  • malloc vs new in c++

To provide flexibility to the programmers, Dynamic Memory Allocation(DMA) is an important concept.

 

It allocates memory in the Heap. Its application is wide like you can use for variable-length array as well for Data Structures like a linked list, tree.

 

C uses calloc() and malloc() for DMA.

C++ also has this along with new & delete operators for allocating and free memory.

 

Unused memory needs to be de-allocated otherwise there will be a Memory Leak issue

Lets learn a bit more about malloc and new in c++ along with their syntax.


Malloc() in C++

malloc() in C++ is a library function used for allocating memory dynamically.

 

Malloc() in C++:

  • allocates a block of memory, but doesn't initialize.
  • and returns a pointer of void.

malloc syntax

ptr =(datatype*) malloc(size);

New in C++

New in C++ is an operator used to request for memory allocation.

 

If memory is free,

  • new operator initializes memory and
  • returns the address of new allocated space.

new syntax

pointer_var = new datatype;

Difference between malloc and new

Lets see the difference between malloc and new in c++.

Serial No.

malloc()

new

   1

malloc() doesn’t call constructor

new calls constructor

   2

malloc() is a function

new is a operator

   3

malloc() returns void pointer

new returns same data type

   4

On failure condition it returns NULL

It returns bad_allocation

 


cpp interview questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Subhajit Guha Thakurta
Page Views :    Published Date : Jan 24,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!