Ilyas Kussainov
Ilyas Kussainov

Reputation: 1

Run time memory allocation error

The code above has been compiled successfully, but when I try to run it, it throws a malloc error:

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

It looks like I was trying to destroy some objects that were not initialized, but I couldn't figure out how to fix it.

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

Upvotes: 0

Views: 145

Answers (1)

Ed Heal
Ed Heal

Reputation: 60007

If you look at your destructor - you have an error

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

So write the following

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

EDIT

As pointed out pop needs some work. i.e.

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

Upvotes: 2

Related Questions