1

I am writing a program that implements stacks as linked lists. The program complies but when I run it, it crashes. I ran the debugger and says unhandled exception when it gets inside the Pop() function and to the line "topPtr = topPtr->next". I was wondering if anyone noticed something in there that is causing this error. I attached the portion of main and the pop function that I believe i sbeing affected. thanks

template<class ItemType>
struct NodeType
{ 
   ItemType info;
   NodeType* next;
};

template<class ItemType>
class Stack
{ 
private:
   int stacklength;
   NodeType<ItemType>* topPtr; // It points to a singly-linked list
public: 
    void Pop(ItemType &x);

template<class ItemType>
void Stack<ItemType>::Pop(ItemType &x)
{
    NodeType<ItemType>* tempPtr;
    tempPtr = topPtr;
    topPtr = topPtr->next;
    delete tempPtr;
    stacklength--;
}

int main()
{
Stack <int> IntStack;
int x;
IntStack.Pop(x);
}
3
  • 1
    That would happen if topPtr is nullptr or uninitialized. So 1: you need to make sure you initialize topPtr = nullptr; in the constructor and 2: you need to check stack depth on Pop (can't pop from an empty stack!). Commented Dec 2, 2015 at 20:16
  • topPtr is not initialized! Commented Dec 2, 2015 at 20:16
  • What do you expect topPtr to point to? Commented Dec 2, 2015 at 20:23

1 Answer 1

1

First off, you don't initialize your pointers.

template<class ItemType>
struct NodeType
{ 
    //...
    NodeType() : next(nullptr) {} ///Initialize next so we can check for null
};

template<class ItemType>
class Stack
{ 
public:
    Stack() : topPtr(nullptr), stacklength(0) { } ///initialize
    //...

Then, in your Pop, you need to check for an empty stack (you can't pop if there are no elements).

template<class ItemType>
void Stack<ItemType>::Pop(ItemType &x)
{
    if (!topPtr)
    {
        //Here, we need to decide how to handle this.
        //One way would be to throw an exception,
        //another way would be to change the method signature
        //and return a bool.
    }
    ///...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.