Linked List, Access Segmentation Fault, Run time error

I am trying to implement a linked list with size(defined 10 in this case) items
The code compliles fine but gives a run time error at the bolded comment below.
When i debug it gives the message as given in comment. Can somebody suggest what's going on? Why is the memory not accesible?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  for ( int i = 0; i < size; i++)
    {
        link t = new Node ((1+rand()%100), 0);
        cout << t->info << endl;
        if ( i == 0)
        head = t;
        t = t->next;   
    }
    link m = head;    
    for ( int j = 0; j < size; j++)
    {
        cout << m->info; /*///ERROR/////-- An Access Segmentation Fault occured in your program -------------*/
        m = m->next;
    }
1
2
3
        link t = new Node ((1+rand()%100), 0);
        ...  
        t = t->next; 


Does that really make sense to you? Note that t stops existing one line later.
Last edited on
here you go, i didn't insert the full code

here's the definition of Node
1
2
3
4
5
6
7
8
9
10
class Node
{
      public:
      Node(int a, Node *b){ info = a; next = b;}
      int info;
      Node* next;
      
             
};
Last edited on
Here's the complete source code

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
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

static const int size = 10;

class Node
{
      public:
      Node(int a, Node *b){ info = a; next = b;}
      int info;
      Node* next;
      
             
};
typedef Node* link;

int main()
{
    srand(time(0));
    link head = 0;
    for ( int i = 0; i < size; i++)
    {
        link t = new Node ((1+rand()%100), 0);
        cout << t->info << endl;
        if ( i == 0)
        head = t;
        t = t->next;   
    }
    link m = head;    
    for ( int j = 0; j < size; j++)
    {
        cout << m->info;
        m = m->next;
    }
}
Are you sure m->info is set to something sensible? Are you sure head->info is set to something sensible before you copy head into m?

I don't see anything in your code that sets link::info anywhere. You haven't shown us the definition of link::info, nor of the constructor for Node, nor of the copy constructor for link, so we can't possibly know how it's being set.

Edit: Ninja'd.
Last edited on
On line 25, t is set to point to a Node who's next pointer is null (0).

On line 28 on the first iteration of the loop, head is set to point to a Node who's next pointer is null.

On line 29, t is set to null.

Nowhere in there is there a possibility of a next pointer being anything but null.
Topic archived. No new replies allowed.