Home »

What is diff between malloc()/free() and new/delete?

Question ListCategory: cWhat is diff between malloc()/free() and new/delete?
adamemliy16 author asked 2 years ago
1 Answers
jeanderson295 author answered 1 year ago

malloc allocates memory for object in heap but doesn't invoke object's constructor to
initiallize the object.

new allocates memory and also invokes constructor to initialize the object.

malloc() and free() do not support object semantics

Does not construct and destruct objects

string * ptr = (string *)(malloc (sizeof(string)))

Are not safe

Does not calculate the size of the objects that it construct

Returns a pointer to void

int *p = (int *) (malloc(sizeof(int)));

int *p = new int;

Are not extensible

new and delete can be overloaded in a class

"delete" first calls the object's termination routine (i.e. its destructor) and then releases the

space the object occupied on the heap memory. If an array of objects was created using

new, then delete must be told that it is dealing with an array by preceding the name with an

empty []:-

Int_t *my_ints = new Int_t[10];

delete []my_ints;

Please login or Register to Submit Answer