C++ use of Malloc/Realloc and Free

Kevin D. Clark kclark at CetaceanNetworks.com
Mon Jun 23 08:26:51 EDT 2003


Derek Martin <blu at sophic.org> writes:

> On Sun, Jun 22, 2003 at 04:15:57PM -0400, Jerry Feldman wrote:

> > Yes, you are quite correct. The bottom line is that the programmer must
> > understand the issues. 
> 
> Ok, I'll bite.  What are the issues?  I've not done much C++
> programming, but I'm curious...

In C++, *operators* like new, delete, and delete[] call a memory
allocation routine *and* invoke something called a constructor (or
destructor).  Memory allocation *functions* (called from a C++) do
just what they do in C -- allocate memory.

If you understand what the notion of an object is, you should just
know that a constructor is a thing that sets an object up (and its
associated resources), and a destructor is a thing that cleans an
object up before it goes away (and its associated resources).

The problem with combining C memory allocation functions (malloc(),
realloc(), free(), etc.) with C++ objects is that these functions
don't know anything about C++ -- so if you use these functions to
allocate/deallocate memory for a C++ object the appropiate
constructor/destructors aren't invoked.  In the case of creating an
object, this will likely lead to a malformed object.  In the case of
destroying an object, this will lead to the object not getting cleaned
up properly.

That's not to say that invoking a C memory allocation routine is
illegal C++ code, but you need to understand what you're doing.

--kevin
-- 
"If you think C++ is not overly complicated, just what is a 'protected
 abstract virtual base pure virtual private destructor', and when was
 the last time you needed one?"
	    -- Tom Cargill, C++ Journal, Fall 1990




More information about the Discuss mailing list