Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between Malloc and new operator to allocate a memory? [duplicate]

Tags:

c++

visual-c++

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

I was confused when I create an object by using new operator in C++. There must be difference between malloc and new operator that would allow me to resize the memory block. If I want to allocate a memory I use malloc but what if I use a new operator?

İsn't it allocate a memory? Can you explain that when shoul I use malloc and when should I use new ?

X* ptr = new(1,2) X;

obj = (ObjID *)malloc( sizeof(ObjID) );

thanks so much.

like image 338
zibib Avatar asked Jan 24 '26 21:01

zibib


2 Answers

In C++ you should always use new and pair it with delete.

  • It calls constructor(s) for the object(s).
  • Since it is an operator, it can be overloaded.
  • It throws exceptions, but there is an exceptionless version.
  • There is a "placement new", which allows you to put your object in already allocated memory.
like image 82
Dark Avatar answered Jan 27 '26 12:01

Dark


new allocates memory and also calls the class constructor for the type you are allocating.

like image 36
Jim Buck Avatar answered Jan 27 '26 11:01

Jim Buck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!