堆栈列表调试断言失败 C++

stack list debug assertion failed c++

当我尝试 运行 我的代码时,它显示调试断言失败。任何人都可以帮助我,我正在做堆栈列表,在头文件中,我创建了一个具有三个变量的结构,字符串* s, int numoflength, stackFrame * next

     void Stack::push(string& s)
        {

            StackFramePtr temp_ptr;
            temp_ptr=new StackFrame;
            temp_ptr->str=new string[s.size()];
            (temp_ptr->str)[0]=s;
            cout<<temp_ptr->str[0]<<endl;
            temp_ptr->num_char=sizeofstring(s);
            if(empty())
            {
                top=temp_ptr;
                temp_ptr->next=NULL;
            }
            else
            {
                temp_ptr->next=top;
                top=temp_ptr;
            }
        }

this is my code about push I think maybe those errors because of this function.
string Stack::pop()
{
    if(empty())
        exit(1);
    string * name;
    StackFramePtr temp;
    temp=top;
    name=top->str;
    top=top->next;
    delete temp;
    return *name;
}

#include <iostream>
#include "stack.h"
#include <string>
using namespace std;
int main()
{
    string str1="to";
    string str2="hi";
    string str3="food";
    string str4="ba";
    string str5="ti";
    string str6="zhilong";
    Stack s;
    s.push(str1);
    s.push(str2);
    s.push(str3);
    s.push(str4);
    s.push(str5);
    s.push(str6);
    cout<<s;
    system("pause");
    return 0;
}

当我尝试 运行 这个主要功能时它给我调试失败,有人可以帮助我吗?非常感谢

class Stack
{
public:
    Stack();
    //Default Constructor used to create an empty Stack object.

    ~Stack();
    //Destructor for Stack objects.

    void push(string& str);

    string pop();

    bool empty();
    //Checks to see if the Stack is empty.  Returns true if empty, else returns false.
    //Stack remains unchanged after function call.


    friend ostream &operator<<(ostream & out_stream, Stack & mystack);

    friend istream &operator>>(istream & in_stream, Stack & mystack);

private:
    StackFramePtr top; // Points to the top of the stack;

};
ostream &operator<<(ostream & outs, Stack & sta)
{
    if(sta.empty())
        exit(1);
    else
    {
        StackFramePtr read;
        read=sta.top;
        while(read!=NULL)
        {
            outs<<"string = "<<read->str[0]<<endl;
            outs<<" number of charcter is" <<read->num_char;
            read=read->next;
            outs<<endl<<endl;
        }
    }
    return outs;
}

push 中,您分配了一个 string 的数组,并将其分配给 Stackstr 成员。在 pop 中,您将 str 复制到 name,然后 delete temp(我假设)将删除名称现在指向的数组。最后,您取消引用这个悬挂指针并访问已经释放的内存。

要解决此问题,请将 name 声明为 string,而不是指向字符串的指针,然后设置 name=*top->strname=top->str[0]