代码之家  ›  专栏  ›  技术社区  ›  Johnrad

带有链表的C++堆栈-内存错误?

  •  2
  • Johnrad  · 技术社区  · 15 年前

    我目前正在编写一个正在使用链表实现的堆栈。我得到这个错误:

    Unhandled exception at 0x75249617 in STACK_LinkedList.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x002ee8f8. 
    

    push() pop() 功能。我找不到我的错误。我对链表还很陌生,所以我很难找到错误。

    推() 功能:

    // Adds an item to the top of the stack
    template <class S>
    void Stack<S>::push(const S & e)
    {
        NodePointer temp = new Node(e);
    
        if ( isEmpty() )
        {
            theTop = theFront = temp;
        }
        else
        {
                // Whatever is after top is stored in temp to keep track of it
            theTop->next = temp;
    
                // TheTop is stored in temp
            theTop = temp;  
            delete temp; 
        }
    }
    

    这是我的 功能:

    //Takes the item off the top of the stack
    template <class S>
    void Stack<S>::pop()
    {
        if ( !isEmpty() )
        {        
                    //temp node is set equal to the front
            NodePointer temp = theFront;
    
                    //Holds the second to last node in the linked list
            NodePointer pred;
    
                    //loops through until the node after temp is 0
            while (temp->next != 0)
            {
                            //sets the second to last as temp
                pred = temp ;
    
                            //basically "increments" temp to the next node
                temp = temp->next ;
            }
    
                    //sets temp equal to the top
            temp = theTop;
    
                    //the top is then set to its predecessor
            theTop = pred;
    
                    //deletes what was known as the top
            delete temp;
        }
    
        else
            cout << "STACK IS EMPTY" << endl;
    
    }
    

    2 回复  |  直到 15 年前
        1
  •  2
  •   Vlad    15 年前

    你不应该删除 temp 在里面 push ! 这是名单的一部分。因此,当您稍后访问这些数据时,肯定会出现异常。

    其次,必须初始化 pred NULL 在里面 pop() ,否则将得到一个未定义的值 theTop

    第三,你应该删除 弹出() 在中分配的节点 push() .

    弹出() . 你的代码应该是这样的:

    void push(data)
    {
        allocate new top
        new top's next is the old top
        store new top in the class
    }
    
    void pop()
    {
        if empty, ERROR;
        new top = old top's next
        deallocate old top
    }
    

    注意你不需要 theFront

        2
  •  2
  •   Dan8080    15 年前

    您的推送功能正在删除“temp”。但是,temp指向刚刚添加到列表中的数据。如果对指针调用delete,则不是丢弃指针,而是删除指针指向的内存!在push中去掉delete语句,然后首先测试它(不带pop)。我还没有检查过您的pop函数,但我将把它留给您在测试pop()之后检查错误的练习。

    -丹8080