I'm solving an exercise in which I have to build a stack using a pointer list. I have to define a struct (I named it 'stack') containing an int value and a pointer to next struct element.
Adding a new value to the stack means creating a new stack element, setting it's link to a pointer to the previously uppermost stack element and updating the pointer variable which always points to the uppermost stack element. Taking an element from the stack means returning the value of the uppermost element, deleting it and refreshing the pointer variable which points to the uppermost stack element.
My stack already works fine. The problem is that I don't know how to proper delete stack elements. Does line 86: delete [] tmp; what it should, namely delete the previously uppermost stack element (i.e. freeing the space allocated for it)? How do I properly free the memory allocated in this program?
First of all, your push/pop/size/clear functions should be members of your stack class. Your val and link* items should be a different class ('element' or so). Then, the elements take care of links and values, while the stack class provides the interface (and a pointer to the last element).
On your question: I think most people do it by having each element clean its own memory in the destructor.
Thanks for the suggestions regarding the stack class, but the Beginners Course I'm taking hasn't progressed to custom classes yet (but I'm sure it soon will), so I'll just leave it like I have it for the moment.
What exactly do you mean by "having each element clean it's own memory in the destructor"?
Line 84 delete [] tmp; is incorrect because only a single stack element is allocated to each stack*, not an array of them. Use delete tmp; instead.
The clear() should iterate through the stack and delete each stack element as it goes, like this:
1 2 3 4 5 6 7 8 9
void clear (void)// this function deletes every element from the stack
{
while( TOP )
{
stack* tmp = TOP;
TOP = TOP->link;
delete tmp;
}
}
Line 84 should do nothing else but delete one single stack element. You confuse it with the clear() function which should delete all stack elements at once.
Line 84 is part of the pop() function which returns the value of the uppermost stack element and then deletes this element, making the previously second-uppermost element the new uppermost element. My question is: Does line 84 really delete the stack element to which tmp is a pointer, or does it just delete the pointer, leaving the stack element itself in place?