Q:

What is the difference between new and malloc in c++?

0

What is the difference between new and malloc?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

See the following comparison chart for malloc and new (malloc vs new):

Feature new malloc
Supported language C++ specific features Supported by both C and C++
Type new is an operator that takes a type and (optionally) a set of initializers for that type as its arguments. malloc() is a library function that takes a number (of bytes) as its argument.
Returns Returns a pointer to an (optionally) initialized object of its type which is type-safe. It returns a void* pointing to uninitialized storage which is type unsafe.
On failure It throws bad_alloc exception on failure. Returns NULL
Required size Calculated by compiler Must be specified in bytes
Handling arrays Has an explicit version Requires manual calculations
Use of constructor Yes. Operator new call the constructor of an object. No
Overridable Yes. No
Deallocation memory allocated by malloc() is deallocated by free(). Objects created by new are destroyed by delete.
Initialization The operator new could initialize an object while allocating memory to it. The malloc returns an uninitialized block of memory.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Interview Questions and Answers(2022)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
What is the difference between delete and free in ... >>
<< What is a “new” keyword in C++?...