2

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.

Community
  • 1
  • 1
zibib
  • 2,035
  • 3
  • 17
  • 15

4 Answers4

4

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.
Dark
  • 195
  • 7
2

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

Jim Buck
  • 20,482
  • 11
  • 57
  • 74
2

new will not only allocate you memory for objects but will also call the constructor on the objects created. malloc will just allocate you a block of memory of the given size with no guarantee of the contents.

Will A
  • 24,780
  • 5
  • 50
  • 61
1

malloc gives you raw memory with garbage bytes left around. New uses malloc internally, too. Use malloc if raw memory is all you need.

alxx
  • 9,897
  • 4
  • 26
  • 41