Z
Z
ZelibobA17062016-10-17 21:08:51
C++ / C#
ZelibobA1706, 2016-10-17 21:08:51

What is the correct way to clean up memory when working with the stack (ADT)?

The implementation of the stack through the list. The push works, but as I understand it, there is a memory leak. And I can't figure out how to fix it. Can anyone suggest?

template<typename T>
struct Node
{
    T data;
    Node<T>* next;
};

template <typename T>
class MyStack
{
private:
    Node<T> node;
    int max;
    int top;
public:
    MyStack(int maxSize = 100);

    inline T pop();
    inline bool push(T value);
};

template<typename T>
MyStack<T>::MyStack(int maxSize)
{
    max = maxSize;
    top = 0;
}

template<typename T>
inline T MyStack<T>::pop()
{
    if (top > 0)
    {
        T data = node.data;
        Node<T>* temp = node.next;
        //delete node;
        node = *temp;
        top--;
        return data;
    }
    return NULL;
}

template<typename T>
inline bool MyStack<T>::push(T value)
{
    if(top >= max) return false;
    Node<T>* tempNode = new Node<T>;
    *tempNode = node;
    node.data = value;
    node.next = tempNode;
    top++;
    return true;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2016-10-17
@ZelibobA1706

And if the comment //delete node; replace with code that actually deletes the node?
Well, push() is wrong. The node must be stored as a Node<T>* pointer, initialized to NULL in the constructor, in push:

tempNode->data = value;
tempNode->next = node;
node = tempNode;

A
Ariox41, 2016-10-18
@Ariox41

I recommend reading about std::unique_ptr
Here is a c++11 version

#include <memory>

template<typename T>
class Stack{
public:
  Stack(std::size_t maxSize_): maxSize(maxSize_){}

  // Что происходит, когда стек пуст? Можно бросить исключение, или сделать как в std
  T pop(){
    // if (!tmp) throw ...
    auto tmp = std::move(head);
    // Обратите внимание, теперь head пуст
    head = std::move(tmp->next);
    // Теперь tmp->next пуст
    --size;
    return tmp->value;
  }

  bool push(T value){
    if (size+1 > maxSize)
      return false;

    // здесь может быть брошено исключение из-за нехватки памяти
    std::unique_ptr<Node> tmp(new Node(value));

    tmp->next = std::move(head);
    head = std::move(tmp);
    ++size;
    return true;
  }

private:
  struct Node{
    T value;
    std::unique_ptr<Node> next = nullptr;
    Node(T value_) noexcept
      : value(value_)
    { }
  };

  std::unique_ptr<Node> head = nullptr;
  std::size_t maxSize;
  std::size_t size = 0;
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question