NEW:
- calls constructor
- It is an operator
- Returns exact data type
- on failure, Throws bad_alloc exception
- size is calculated by compiler
malloc() :
- does not calls constructors
- It is a function
- Returns void *
- On failure, returns NULL
- size is calculated manually
Shathana. S.R. Answered question July 6, 2023
new is faster than malloc() because an operator is always faster than a function.
Sandhya Answered question July 6, 2023
The main differences between new and malloc() are:
newis type-safe and automatically calculates the required memory size based on the object type, whilemalloc()is not type-safe and requires manual size specification in bytes.newcalls the constructor of the object being created, ensuring proper initialization, whereasmalloc()does not invoke any constructor.newreturns a pointer to the type being allocated, whilemalloc()returns avoid*pointer that requires a typecast.newthrows astd::bad_allocexception if memory allocation fails, whilemalloc()returns aNULLpointer for error checking.newis preferred in modern C++ programming, butmalloc()may be necessary when working with legacy code or interfacing with C libraries.
Riya Answered question July 6, 2023
malloc(): It is a C library function that can also be used in C++, while the “new” operator is specific for C++ only. Both malloc() and new are used to allocate the memory dynamically in heap. But “new” does call the constructor of a class whereas “malloc()” does not.
BrindhaPrathaban Answered question June 30, 2023
malloc() is a C library function that can also be used in C++, whereas the “new” operator is only available in C++. Both malloc() and new are used to dynamically allocate memory in heap. However, “new” invokes the constructor of a class, whereas “malloc()” does not.
Vishalini.R Answered question June 28, 2023
