C++ use of Malloc/Realloc and Free

nmeyers at javalinux.net nmeyers at javalinux.net
Mon Jun 23 18:20:37 EDT 2003


On Mon, Jun 23, 2003 at 05:48:14PM -0400, Glenn Burkhardt wrote:
> > On Sun, Jun 22, 2003 at 04:15:57PM -0400, Jerry Feldman wrote:
> > > > So I agree with you that using malloc/free/realloc can be quite
> > > > dangerous, there are some occasional times where the risks outweigh
> > > > the danger. 
> > > 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...
> > 
> > - -- 
> > Derek D. Martin
> 
> I don't think it's very complicated, but as always, one needs to be aware of
> what happens.  Just make sure that if you allocate memory within a class, that
> the destructor for the class frees it.  Sort of like making sure that memory 
> allocated by a function is released before it returns.  If pointers to 
> allocated memory are passed around between classes, the same problems
> exist as for passing pointers to allocated memory between C functions.  One
> doesn't want it freed in a destructor and then used, or have it left dangling.

Constructors and destructors can do anything from manage memory to
launch missiles - they are whatever the programmer wants to be executed
automatically when objects go into and out of existence (either in
the heap or on the stack). So, in the general case, it *can* be very
complicated. Using malloc/realloc/free bypasses that mechanism and can
completely change the function of the object. That's the issue: you have
to understand what functionality you're short-circuiting.

Nathan Meyers
nmeyers at javalinux.net



More information about the Discuss mailing list