Segmentation Fault When Attempting to Print a Linked List

The problem code in question is:

currnode = ((currnode)->next); 

in my printlist function. Every time I try to change the value of my current node to the next node, I receive a segmentation fault. Why is this? I've played around with the pointers and have done some searching online to no avail.

#include<stdio.h>    
#include<stdlib.h>
#define RANGE 1000

 typedef struct lnode {
   int value; struct lnode *next;
      } lnode;

void printlist(lnode *list);
void search();

int main(int argc, char *argv){

   time_t t;
   srand((unsigned) time(&t));
  int i, times, num, a, b;
   lnode **leven, **lodd;    

   printf("Please state the amount of numbers to be printed\n");   
   scanf("%d", &times);


   for(i = 0; i < times; i++){

      lnode **crnt, **pred;
      a = nextnum();      
      b = (a & 1);

      if (b == 0){


            printf("even\n"); 
            printf("The value of the even node is: %d\n", a);
        /*    search(*leven,**crnt,**pred, a); */
            insertatfront(&leven, a);


         }else{

           printf("odd\n");
           printf("The value of the odd node is: %d\n", a);
          /* search(&leven,crnt, pred, a);*/
           insertatfront(&lodd, a);

      }

   }

   printlist(*lodd); 
   printlist(*leven);  
}

int nextnum(){

   int i, rand1, num;

   rand1 = rand()%RANGE;  
   return rand1;
}

void getnode(lnode **ptr)
{

 *ptr = malloc(sizeof(lnode));

}



int insertatfront(lnode **list, int x){

   lnode *new_node, **pred, **crnt;

   getnode(&new_node);

   if(!new_node) return 0;

   new_node->value = x;
   new_node->next = *list;

   printf("The node at the next is %d\n", new_node->next->value);


   *list = new_node;

    /*search(*list,&crnt,&pred, x);*/

}

void printlist(lnode *list){

   int *val;

   int print;
   struct lnode *tmp;
   lnode *currnode;


   currnode = list;

   while(currnode != NULL){

     val = &((currnode)->value);

     printf("%d\n", val);


     currnode = ((currnode)->next);
     printf("printed successfully\n");    

    }
   printf("done \n");

  }



void search(lnode *list, lnode **crnt, lnode **pred, int x)
   {
        *crnt = list;
        *pred = NULL;

           while(*crnt) {
                 if((*crnt)->value == x) return;
                  *pred = *crnt;    *crnt = (*crnt)->next;
            }
      }

Answers


You probably need to increase your warning level. There are some clear problems. For example:

insertatfront(&leven, a);

insertatfront() takes a lnode**, but &leven is a lnode***.


last node's next is not null,it's an undefined value,so when the programm execute undefinedValue.next,segmentation fault happened.


Need Your Help

parsing nested oval file with XML::Twig

xml perl xml-twig

I have the following OVAL definintion and want to parse it and store it on specific perl object like a array ref and then accessing it as object