From b4bc3b01fda896ef8325608a7691db493704ba0f Mon Sep 17 00:00:00 2001 From: "piotr.idzik" Date: Wed, 12 Oct 2022 19:23:35 +0200 Subject: [PATCH] fix: remove memory leak in stack --- data_structures/stack.h | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/data_structures/stack.h b/data_structures/stack.h index 483648046..e7b8572bb 100644 --- a/data_structures/stack.h +++ b/data_structures/stack.h @@ -47,10 +47,6 @@ class stack { explicit stack(const stack &otherStack) { node *newNode, *current, *last; - /* If stack is no empty, make it empty */ - if (stackTop != nullptr) { - stackTop = nullptr; - } if (otherStack.stackTop == nullptr) { stackTop = nullptr; } else { @@ -73,8 +69,20 @@ class stack { size = otherStack.size; } + private: + void delete_all_nodes() { + node *curNode = stackTop; + while (curNode != nullptr) { + const auto tmpNode = curNode->next; + delete curNode; + curNode = tmpNode; + } + stackTop = nullptr; + } + + public: /** Destructor */ - ~stack() {} + ~stack() { delete_all_nodes(); } /** Determine whether the stack is empty */ bool isEmptyStack() { return (stackTop == nullptr); } @@ -109,16 +117,16 @@ class stack { } /** Clear stack */ - void clear() { stackTop = nullptr; } + void clear() { + delete_all_nodes(); + size = 0; + } /** Overload "=" the assignment operator */ stack &operator=(const stack &otherStack) { node *newNode, *current, *last; - /* If stack is no empty, make it empty */ - if (stackTop != nullptr) { - stackTop = nullptr; - } + delete_all_nodes(); if (otherStack.stackTop == nullptr) { stackTop = nullptr; } else {