2017-02-19 126 views
0

上面的代碼已經被編譯成功,但是當我嘗試運行它,它拋出一個malloc錯誤:運行時內存分配錯誤

malloc: * error for object 0x7fdbf6402800: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug

它看起來像我試圖摧毀那些不某些對象初始化,但我無法弄清楚如何解決它。

#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(); 
} 
+0

歡迎來到Stack Overflow。請花些時間閱讀[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –

+0

解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –

回答

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