Use new
. You should never need to use malloc
in a C++ program, unless it is interacting with some C code or you have some specific reason to manage memory in a special way.
Your example of node = malloc(sizeof(Node))
is a bad idea, in because the constructor of Node
(if any exists) would not be called, and a subsequent delete node;
would not work properly.
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.