Segmentation error but why

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
41
42
43
44
45
46
47
48
void stack:: pushsort(int item)
{
         node *t=new node;


        cout<<"your function is calling"<<endl;
        if(head == NULL)
        {       cout<<"test"<<endl;
                t->next=head;
                t->data=item;
                head=t;
        }
        else if(item <= head->data)
                {
                cout<<"test2"<<endl;
                t->data=item;
                t->next=head;
                head=t;
                }
        else   // insert in the middle or end
                {

                        cout<<"test3"<<endl;
                  t= head;
                  node* trailt=new node;
                  while( item > t -> data && t != NULL )
                    {

                        cout<<"test4"<<endl;
                        trailt = t;
                        t = t -> next;  // move to the next cell

                      if( t->next == NULL)
                          {
                                cout<<"test5"<<endl;
                                t->data=item;
                                trailt->next=t;

                        }
                     }  // end while
                cout<<"test6"<<endl;

                   t->data=item;
                   trailt->next=t;
                   t->next=t;
               }

}


the code is supposed to make a linked list and when pushing number into it it checks the rest so that the numbers are inserted in numerical order from least to greatest. Not sure exactly whats causing the error
I think that on lines 44 & 45 you are failing to properly set t's next member. Even if t is inserted into the middle of the of the list, t->next is still set to t, breaking the list. I believe you would want something like:
1
2
t->next = trailt->next;
trailt->next = t;

I'm not certain how that would cause a segmentation fault, however. What line is causing the problem?
i tried but no difference in the output it completely skips past test and test 2 and then ends before printing out test 5 so it doesn't even get to lines 44 and 45
The problem is line 26:

 
while( item > t -> data && t != NULL )


Order of evaluation is left to right; first you check if item > t->data, and THEN you check to see if t is NULL. If it was null, the first check would crash.

Aside from that, line 25 is a memory leak; there is no need to allocate a new node.
Last edited on
Topic archived. No new replies allowed.