How to use malloc()
in C++ program?
You shouldn't use malloc
in C++. You should use new
instead.
In fact, you probably shouldn't be using new
as well (for most basic programming in C++). But still a basic example is declaring an array: int* array = new int[n]
. This will allocated room for n integers and return a pointer to the address of the first one. Please note that you must explicitly call delete[]
to free this allocation.
Mostly, you shouldn't use it at all. C++ provides the new
and delete
operators for memory management, and even delete
can be largely avoided by using smart pointers such as boost::shared_ptr
from the Boost library.
Example:
// malloc
Duck* duck = (Duck*)malloc(sizeof(Duck));
// new
Duck* duck = new Duck();
Also note that, if the Duck class has a non-trivial constructor, then new
is almost mandatory. (Almost, because you could use malloc
with placement new
, but that would be getting us off the main track).
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