difference between malloc and new

what is the difference between (malloc and new) and (delete and free)?
simplest difference is malloc allocates memory but does not call the constructor.
new does call constructor

same way free deallocates memory does not call destructor delete does.

malloc/free are from C and C does not have classes and constructors for structs.
C++ does and hence in C++ should always use new/delete.
(I would say use shared_ptr, unique_ptr but C++11 capable compilers are not commonplace yet)
Malloc purely allocates memory for you to use. You tell it how many bytes you need and it returns a void*, which you have to cast.
New instantiates an object by allocating enough memory for it and then calling its constructor. It's much higher level than malloc.

Delete is the opposite of new, and calls the objects' destructors before deallocating the memory.
Free just takes a void* and deallocates the block of memory the pointer points to.
Last edited on
Topic archived. No new replies allowed.