Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: is malloc equivalent to new? [duplicate]

Tags:

c++

Possible Duplicate:
What is the difference between new/delete and malloc/free?

I am a noob in c++, want to know whether

memblock = (char *)malloc( currentByteLength); 

is equivalent to

memblock = new char[currentByteLength]

in c++?

like image 478
karthick Avatar asked Dec 03 '22 03:12

karthick


1 Answers

memblock = (char *)malloc( currentByteLength); 

memblock = new char[currentByteLength];

No difference now. But if you replace char with int, then yes, there would be difference, because in that case, malloc would allocate memory of size currentByteLength, while new would allocate memory of size size(int) * currentByteLength. So be very very careful.

Also, if the type you mention in new expression, is user-defined type, then the default constructor would be called currentByteLength number of times, to construct the objects!

For built-in types, there is no constructor!

like image 93
Nawaz Avatar answered Dec 26 '22 14:12

Nawaz