Linked List seg fault

I'm using a linked list as follows:
1
2
3
4
5
6
typedef struct node* Link;

struct node{
  long dist;
  Link next;
};


I have also defined the following functions:
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
void init(Link l){
  l = new node;
  l->next = NULL;
}

Link search(Link l,  long d){
  Link tmp;
  tmp = l->next;
  
  while(tmp != NULL || tmp->dist !=d){
    tmp = tmp->next;
  }
  return (tmp);
}

void insert(Link l[], long x, long y, long d, long col){  
  for( long i=0; i<col; i++){
    if(search(l[i], d) != NULL){
      cout << "insert failed" << endl;
      return;
    }
  }
  
  Link prev1, prev2;
  Link tmp1 = new node;
  Link tmp2 = new node;
    
  prev1 = preceed(l[x], d);
  tmp1->dist = d;
  tmp1->next = prev1->next;
  prev1->next = tmp1;
  
  prev2 = preceed(l[y], d);
  tmp2->dist = d;
  tmp2->next = prev2->next;
  prev2->next = tmp2;
}


In the main function, I have created an array of linked lists (which I'm not sure if I've done right):
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
int main(){
  long col, ghost, x, y, d;
  string command;
  cout << "read file" << endl;
  ifstream ifs("ghostleg.txt");
  
  if(ifs.fail()){
    cerr << "Failed to open ghostleg.txt" << endl;
		exit(1);
  }
  
  ifs >> col;
  Link *player = new Link[col];
  
  for(long i=0; i<col; i++){
    init(player[i]);
  }  
  
  ifs >> ghost;
  for(long i=0; i<ghost; i++){
    ifs >> x;
    ifs >> y;
    ifs >> d;
    insert(player, x-1, y-1, d, col);
  }
  return 0;
}


However, when I run the program, after it calls the insert function, calls the search function, and reaches the statement "tmp = l->next;", it seg faults (according to debugger). I've been thinking for hours but I can't seem to see why it seg faults. Could somebody please help me?
Because you're dereferencing a pointer that is either NULL, or pointing to memory that isn't yours.
Do you mean when I make a dummy node?
Not a scooby. I can't test your code myself because it's missing the preceed function. When you're causing a segFault and you're doing it with a pointer, that's how it's done; NULL dereference or memory that isn't yours.
closed account (D80DSL3A)
You are passing the Link to the init() by value so the assignment l = new node; does not change player[i] on line 16 in the main().

Try passing by reference. Change the init() to: void init(Link& l).
That should get you past the 1st problem, though I see others waiting for you to discover.

EDIT: Correction to code line cited.
Last edited on
Topic archived. No new replies allowed.