2017-02-19 6 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

ようこそスタックオーバーフロー。 [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; 
    } 
} 

EDIT

としては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; 
}