I am transitioning to C++ from C. In C++, is there any use for the malloc function? Or can I just declare it with the "new" keyword. For example:
class Node
{
...
}
...
Node *node1 = malloc(sizeof(Node)); //malloc
Node *node2 = new Node; //new
Which one should I use?
Use new
. You shouldn't need to use malloc
in a C++ program, unless it is interacting with some C code or you have some reason to manage memory in a special way.
Your example of node = malloc(sizeof(Node))
is a bad idea, because the constructor of Node
(if any exists) would not be called, and a subsequent delete node;
would have undefined results.
If you need a buffer of bytes, rather than an object, you'll generally want to do something like this:
char *buffer = new char[1024];
or, preferably, something like this:
std::vector<char> buffer(1024);
Note that for the second example (using std::vector<>
), there is no need to delete
the object; its memory will automatically be freed when it goes out of scope. You should strive to avoid both new
and malloc
in C++ programs, instead using objects that automatically manage their own memory.
The direct equivalent of malloc()
in C++ is operator new()
which also allocates raw memory, however in most cases a new
expression is what you want. A new
expression both allocates an appropriate amount of raw memory and initializes an object in that memory location, returning a correctly typed pointer to the new object.
In your case , new Node
is correct as it allocates memory and initializes a new Node
object. Simply calling malloc
and casting result to a pointer to Node
won't correctly construct the Node
object. This is critical if Node
is not a POD-struct (e.g. when it or one of its sub-objects has a constructor that should be called).
You should avoid dynamic allocation where it is not needed; where it is needed, it is often best to initialize some sort of smart pointer with the address of the dynamically allocated object so that it's not possible to 'forget' to delete
the obejct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With