On Fri, Mar 28, 2008 at 4:02 PM, Ignacio <[EMAIL PROTECTED]> wrote:
[...]
> I'm reading "Data Structures and Program Design in
> C++" by R. Kruse and A. Ryba. On page 129 the
> following code for the push method of a linked stack
> is presented:
>
> 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.
> 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.)
> 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.
--
PJH
A man in a shellsuit goes into a posh furriers. He says to the shop
assistant "I want a coat".
The shop assistant, barely concealing her disdain, asks "What fur?"
The man replies "Fur ma girlfriend".