-3

What is the difference between several alloc methods of memory in c++?

like so new, malloc and so on ...

thx

  • 3
    Information about each is pretty easy to find, as well as what happens when you mix them. – chris Sep 08 '13 at 04:14

1 Answers1

0

malloc allocates uninitialized memory. Malloc is not type safe

new initializes the allocated memory by calling the constructor. Also new keyword is type safe

delete is used to deallocate memory from the heap.

NOTE:- new and delete are C++ specific features.

Besides many other point which you may want to see. Here is one point which is worth reading

[16.4] Why should I use new instead of trustworthy old malloc()?

FAQ: new/delete call the constructor/destructor; new is type safe, malloc is not; new can be overridden by a class.

FQA: The virtues of new mentioned by the FAQ are not virtues, because constructors, destructors, and operator overloading are garbage (see what happens when you have no garbage collection?), and the type safety issue is really tiny here (normally you have to cast the void* returned by malloc to the right pointer type to assign it to a typed pointer variable, which may be annoying, but far from "unsafe").

Oh, and using trustworthy old malloc makes it possible to use the equally trustworthy & old realloc. Too bad we don't have a shiny new operator renew or something.

Still, new is not bad enough to justify a deviation from the common style used throughout a language, even when the language is C++. In particular, classes with non-trivial constructors will misbehave in fatal ways if you simply malloc the objects. So why not use new throughout the code? People rarely overload operator new, so it probably won't get in your way too much. And if they do overload new, you can always ask them to stop.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • More accurately, `new` default-initializes or value-initializes it, or even uses an initial value, depending on how you use it. That's not the only difference, though, and there are more allocation methods than those two. – chris Sep 08 '13 at 04:19
  • Why malloc is not type safe? – choxsword Apr 23 '18 at 10:58