Basically malloc() is used to allocate memory in C, while new is used to allocate memory in C++ langauage.It is frequently asked question in Interview. Difference between malloc and new are as follows.
- malloc() is C function while new is an C++ operator
- malloc() create memory on heap while new create memory on free space.
- malloc() return a void pointer which is implicitly typecast in to any of the data type as C++ is a storng type safe programming language so new operator return the specific type pointer. If malloc()y is used in c++ then its return should be typecast.
- In malloc() size must be specified in term of bytes whicle in new size is calculated by the compiler.
- If malloc() fail it return the NULL while if new fail it throw bad_alloc which is handle safely.
- malloc() didn’t call the constructor while everytime new call the constructor, So system defined data type can also be initialised with new operator.
- memory allocated by malloc() clean by free(ptr) function while memory allocated by new is freed by delete operator.
80 total views, 5 views today