Mail Archives: djgpp/1997/05/28/20:33:40
ferruccio barletta wrote:
>
> Nathan Gray (gray AT ll DOT mit DOT edu) wrote:
> : Since we're on the subject of C and C++, does anyone have a good
> : explanation for the differences between malloc() and new? As a native
> : C++ programmer, my first instinct is to use new, but I see malloc() so
> : often I'm starting to wonder if I'm missing something.
>
> The only difference that I know of between new/delete and malloc/free is
> that new/delete will call the appropriate constructors & destructors
> whereas malloc/free simply allocates & frees memory.
>
> FGB
There are a few other differences.
malloc() returns 0 on failure, the global new throws an exception. The
result is that you do not have to check the return value of new.
'new' is a class operator and can be overloaded on a per-class basis.
This means that some classes might not even allocate memory when new is
called for them (i.e. an IO mapping class might insert itself at a known
address, rather than allocate storage from the heap), others can use
custom memory management technqies. malloc(), on the other hand, is
defined to allocate memory from the free store.
'new' allows you to install a handler callback to handle out-of-memory
conditions, giving you an opportunity to free up unused memory during a
'new' call if new can't allocate sufficient memory.
The following construction:
MyClass *pMyClass = (MyClass *)malloc(sizeof(MyClass));
is undefined for classes with virtual functions.
Jason Shankel,
Maxis, Inc.
- Raw text -