What's The Difference Between malloc() & new?

closed account (zb0S216C)
Consider these two memory allocation requests:

1
2
3
4
5
#include <new>
#include <cstdlib>

int *Memory(static_cast<int*>(std::malloc(sizeof(int))));
int *Memory(static_cast<int*>(operator new(sizeof(int))));

I already know that new is type-safe, but what other differences separate these allocation requests?

Wazzak
new is typesafe, but operator new() isn't.

Like std::malloc(), it's just an allocation function that allocates storage dynamically. The differences are:

They may be allocating storage from different places.
The storage obtained has different requirements for freeing
operator new() can be replaced by the user
behavior on allocation failure is very different
Last edited on
closed account (zb0S216C)
Thanks for the reply, Cubbi :)

A few things:

1) You said that "they may be allocating from different places". Other than RAM, where else could the get memory? Or have I missed the point?

2) What do you mean by: "operator new() can be replaced by the user"?

Wazzak
Last edited on
1) RAM is big. A case I've seen is when a (proprietary implementation of) C++ standard library sets up a different set of VM pages for allocations done with new.

2) operator new() is one of the eight replaceable functions in C++. If you provide your own function with identical signature, any call made to it in the same TU, directly or through new, will use your function.
Last edited on
closed account (zb0S216C)
Thanks again, Cubbi, for your assistance :) You have my gratitude.

Wazzak
Topic archived. No new replies allowed.