malloc - cppreference.com[
^] (Edit: for Memory ALLOCation) is a function from the C standard library to allocate memory from the heap.
It can be still used with C++ but
new
should be used instead (see also
std::malloc - cppreference.com[
^]) .
One difference is that
malloc
returns a
void*
pointer that must be casted to the type on the left side with C++:
struct node *new_node;
new_node = malloc(sizeof(struct node));
new_node = (struct node *)malloc(sizeof(struct node));
new_node = reinterpret_cast<struct node *>(malloc(sizeof(struct node)));
If you compare this with C++
new
new_node = new node;
you will notice the next difference:
There is also no need for the
sizeof()
operator because the compiler knows the type and it's size.
Another difference is that
new
- when called for classes - calls the constructor and allows passing arguments to the constructor.
One thing to observe is that always the corresponding release function must be used (
free
resp.
delete
).