RS wrote:
Hi,
What is the difference between new() and malloc()?
RS
The difference is, malloc() is a function from the C library, while new
is a C++ operator. In fact, there is the operator called 'new' and
there's a function called 'operator new()' which is invoked by the
former each time you allocate memory using 'new'. The latter is also
called 'placement new', because you can give it an address where in
memory to allocate space. Note that it only allocates raw memory like
malloc and does not invoke any ctor calls.
Using malloc() in C++ is problematic for several reasons.
First, it doesn't invoke the constructor of the class you're
instantiating. This is obvious, since it's a C function, and C doesn't
know a thing about constructors.
In other words, it allocates raw memory (like placement new) and returns
a pointer of type void* to the newly allocated space.
Second, you therefore have to cast void* to the pointer type you need,
which you wouldn't have to do when using new instead (this is a GOOD thing).
Third, you have to pass malloc() the amount of memory you want to
allocate. This is error prone, if you don't give it the right size, you
will screw up. new figures out itself how much memory it will have to
allocate.
So, if you don't really care about the whole memory allocation stuff and
don't plan to implement your own allocators, or if you're even remotely
unsure when to use what, the rule of thumb is to prefer 'new' over
malloc() whenever possible.
--
Regards,
Matthias