运行时内存分配错误

时间:2017-02-19 06:45:12

标签: c++

上面的代码已成功编译,但是当我尝试运行它时,它会抛出malloc错误:

  

malloc: *对象0x7fdbf6402800的错误:未释放指针被释放   * 在malloc_error_break中设置断点以进行调试

看起来我试图销毁一些未初始化的对象,但我无法弄清楚如何修复它。

#include <iostream>
template <class T>
class Node {

public:
    T data;
    Node<T>* next;
    Node<T>* prev;

    Node(): data(), next(nullptr), prev(nullptr) { }
    Node(T dt): data(dt), next(nullptr), prev(nullptr) { }
    Node(T dt, Node* n): data(dt), next(nullptr), prev(n) { }

    T get() { return data; }
};

template <class T>
class Stack {

public:
    Node<T>* head;
    Node<T>* tail;

    Stack(): head(nullptr), tail(nullptr) { }
    ~Stack() {
        Node<T>* temp = head;
        while(temp) {
            delete temp;
            temp = temp->next;
        }
    }

    bool empty() const;
    Stack& push(T);
    Stack& pop();
};

template <class T>
bool Stack<T>::empty() const {
    return head == nullptr;
}

template <class T>
Stack<T>& Stack<T>::push(T x) {
    if (head == nullptr) {
        head = new Node<T>(x);
        tail = head;
    }
    // It seems that problem occurs here
    else {
        Node<T>* temp = tail;
        tail = new Node<T>(x, tail);
        tail->prev = temp;
        temp->next = tail;
    }

    return *this;
}

template <class T>
Stack<T>& Stack<T>::pop() {
    if (!head) {
        return *this;
    }
    else if (head == tail) {
        delete head;
        head = nullptr;
        tail = nullptr;
    }
    else {
        Node<T>* temp = tail;
        delete tail;
        tail = temp;
    }

    return *this;
}

int main() {
    Stack<int> istack;
    istack.push(5);
    istack.push(3);
    istack.push(4);
    istack.push(7);
    istack.pop();
}

1 个答案:

答案 0 :(得分:2)

如果你看看你的析构函数 - 你有错误

~Stack() {
    Node<T>* temp = head;
    while(temp) {
        delete temp;
        temp = temp->next; // Here temp is no longer a valid pointer
                           // You have just deleted it!
    }
}

所以写下面的

~Stack() {
    while(head) {
        Node<T>* temp = head->next;
        delete head
        head = temp;
    }
}

编辑

正如所指出的,pop需要一些工作。即。

template <class T>
Stack<T>& Stack<T>::pop() {
    if (!head) {
        return *this;
    }

    Node<T>* temp = tail->next;
    delete tail;
    tail = temp;
    if (!tail) {
        head = nullptr;
    }
    return *this;
}