Need Help With this pointer problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
List* List:: rev(List* c)
{
   List l1;
   cout<<c;
	node* temp = c->head;
   node* ptemp = c->head;
   while(temp!=NULL)
   {
   	int d = c->count();
   	if(temp->next == NULL)
      	{
         cout<<endl;
         node * temp1=temp;
         l1.insert(temp->data);
         temp = c->head;
         ptemp->next = NULL;
         ptemp = temp;
         delete temp1;
         }
      if(temp->next == NULL && c->count()==1 )
        {
        cout<<"data";
        l1.insert(temp->data);
        delete temp;
        temp = NULL;
        ptemp = NULL;
        }
      else
      {
         ptemp = temp;
         temp = temp->next;
      }
   }
   cout<<c<<endl;
   c = &l1;
   l1.display();
   cout<<"ccc"<<endl; cout<<c<<endl;
   c->display();
   return c;
}


1
2
3
4
5
6
7
8
9
10
main () {
      List l,se;
      char s[]="[2,1,6,0,9,3]";
      l.readlist(s);
      List* c = &l;
      List*  d = l.rev(c);
      cout<<d;     
      d->display() // throws runtime thread error.
      return 0;
}


I have reviewed every line at least twice, but can't fix this error. The address of 'c' in rev() function and 'd' in main() function is same, but display() function doesn't execute. Can somebody help??
Your rev() is returning a pointer to a local variable:
1
2
3
4
List l1;
//...
c = &ll;
c->display();// OK here because ll is still in scope 


in main():
1
2
3
List*  d = l.rev(c);// receive invalid pointer
cout<<d;     // get lucky once
d->display()// BOOM! 

I'm not sure how you will want to fix this but I am guessing that's the cause of your runtime error.
thank you so much, sometimes workload makes me forget looking for trivials.
Topic archived. No new replies allowed.