运行时间内存分配错误



上面的代码已成功编译,但是当我尝试运行它时,它会引发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();
}

如果您查看灾难 - 您有错误

~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;
}

最新更新