I am working on stack data structure implementation using linked lists , building destroyStack() function by which i can free all allocated memory once the i finish using stack class as i execute the main i expected to get all the pointers freed after destroyStack() has been called.
class Stack{
private:
int size;
typedef struct Node{
stackType data;
struct Node *last;
} Node;
Node *top;
public:
Stack(){
size = 0;
top = NULL;
}
void push(stackType element){
Node *temp = new Node();
if (!temp)
throw invalid_argument("heap overflow");
if (element != '\0'){
temp->data = element;
temp->last = top;
top = temp;
size++;
}
else{
throw invalid_argument("invalid element");
}
}
stackType pop(){
if (empty())
throw invalid_argument("this is an empty stack");
Node *temp = new Node();
stackType element = top->data;
temp = top;
top = top->last;
temp->last = NULL;
delete(temp);
size--;
return element;
}
void destroyStack(){
Node *temp = top;
while (top != NULL){
top = top->last;
delete(temp);
temp = top;
}
}
};
int main(){
Stack stack;
stack.push(100);
stack.push(90);
stack.push(80);
stack.printStack();
for (int i = 0; i < 3; i++)
cout << stack.pop() << endl;
stack.destroyStack();
return 0;
}
as i use valgrind to check if there any kind of leaks i find this message.
==53372== HEAP SUMMARY:
==53372== in use at exit: 48 bytes in 3 blocks
==53372== total heap usage: 8 allocs, 5 frees, 73,824 bytes allocated
==53372==
==53372== Searching for pointers to 3 not-freed blocks
==53372== Checked 116,952 bytes
so any ideas how can i edit my code to free all the blocks once i used destroy function ?