I am transitioning from C to C++. In C++, is there any use for the malloc
function, or can I just use the new
keyword? For example:
class Node {
/* ... */
};
/* ... */
Node *node = malloc(sizeof(Node));
// vs
Node *node = new Node;
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:
std::unique_ptr<char[]> buffer = std::make_unique<char[]>(1024);
// or alternatively:
std::vector<char> buffer(1024);
Note that for the latter examples (using std::vector
or std::unique_ptr
), 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.
Here are your options and their benefits:
Method | Dynamically Sized | Automatically Managed | Resizable |
---|---|---|---|
std::array<char, N> |
No | Yes | No |
new char[N] |
Yes | No | No |
std::unique_ptr<char[]> |
Yes | Yes | No |
std::vector<char> |
Yes | Yes | Yes |