On Fri, 28 Mar 2008, at 16:28 (GMT), Paul Herring
wrote:

> >  Error_code Stack::push(const Stack_entry &item)
> >  {
> >   Node *new_top = new Node(item, top_node);
> >   if(new_top == NULL) return overflow;
> >   top_node = new_top;
> >   return success;
> >  }
> >
> >  My question: isn't this line:
> >
> >   delete new_top;
> >
> >  needed after the assignment "top_node =
> >  new_top;"?
> 
> No, because the assignment only copies the
> pointer, not what is pointed to. deleting it
> would result in later code accessing freed
> memory.

Right, I understand it now.  Deleting it would free
the memory allocated for the top node of the stack.

If I understand correctly then, the stack will work
fine until that memory is used for something else, in
which case the content of the top node will be
replaced by other data.

> >  Without this extra line, wouldn't garbage mount
> >  up when the function ends and new_top runs out
> >  of scope?
> 
> No - because a copy of the pointer in new_top
> has been made. This isn't a memory leak, which
> is what you think is happening.
> 
> Look for a 'delete top_node;' in the code. (Or
> it may be delete <something else>; - probably in
> the (I'm assuming the name here) stack::pop()
> function.)

Exactly.  The method Stack::pop() uses delete to free
the memory previously allocated for the top node of
the stack.

> >  Nothing is mentioned about this, neither in the
> >  book not in the errata.  How would you check if
> >  you're accidentally accumulating garbage?
> 
> There are tools for checking this. Depends on
> your platform and/or compiler.

I'll look for them.

Thank you for your help, Paul!

Ignacio
Buenos Aires, Argentina





      Lesen Sie Ihre E-Mails jetzt einfach von unterwegs.
www.yahoo.de/go

Reply via email to