stack list debug assertion failed c++ -
when try run code, show me debug assertion failed .any 1 can me, doing stack list,in header file, create struct has 3 variable, string * 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; } } code push think maybe errors because of 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; }
when try run main function give me debug failure, can me?
class stack { public: stack(); //default constructor used create empty stack object. ~stack(); //destructor stack objects. void push(string& str); string pop(); bool empty(); //checks see if stack 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 top of 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; }
in push
allocate array of string
, , assign str
member of stack
. in pop
copy str
name
, delete temp
(i'm assuming) delete array name pointing in to. lastly dereference dangling pointer , access memory has been freed.
to fix this, declare name
string
, rather pointer string, set name=*top->str
or name=top->str[0]
.
Comments
Post a Comment