Mail Archives: djgpp/1997/05/29/00:33:37
Nathan Gray <gray AT ll DOT mit DOT edu> writes:
>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.
Sure. The C standard function "malloc()" attempts to allocate a block
of memory from dynamic storage and returns the address of the newly
allocated block (or 0 if the allocation fails) as a void*. And that's
all it does.
The C++ operator new also allocates a block of memory for a dynamic
object, but with the following advantages over malloc:
operator new knows how big the object is (so you can't
mess up a call to sizeof)
operator new always calls the default constructor of
the object's class, and all of its base classes
operator new returns a pointer of the proper type, so
you don't need to cast
operator new can be overloaded on a class by class basis
to provide special features such as automatic garbage
collection, memory allocation diagnostics, and preformatted
memory pools
Rule of thumb: If you are writing C++ code, always use new instead
of malloc().
--
ciao,
milo
================================================================
John DiCamillo Fiery the Angels Fell
milod AT netcom DOT com Deep thunder rode around their shores
- Raw text -