vendredi 31 juillet 2015

Why segmentation fault is occcuring in following code

This program tries to create separate linked list for each line of input.The first line contains the number of testcases and following lines contains the space separated integers as link list elements

Sample input

2
1 2 4 6
3 9 11 12

Expected Output :

LinkList 1 : 1 2 4 6
LinkList 2 : 3 9 11 12

This function puts each space separated integer line into a string and pass it to makelist function

int main()
{

     int t;
     scanf("%d\n",&t);   //number of testcases
     int x;


     while(t--)
      {
        struct node *head1=NULL,*head2=NULL;

        int i=0,j,k;
        int len1=0,len2=0;
         char str1[200],str2[200];

         fgets(str1,200,stdin);   //input first line
         fgets(str2,200,stdin);   // input second line

        len1=strlen(str1);
          len2=strlen(str2);

       printf("length,of strings %d %d",len1,len2);
       makeList(str1,&head1,len1);    //fault occurs here
        makeList(str2,&head2,len2);
        }

}

//program to make linklist from input string

void makeList(char *str,struct node ** head,int len)
{
   printf("Inside makelist");
   int i ;
   struct node *temp, *temp2;
    for(i=0;i<len;i++)
     {
        if((str[i]>=48 )&& (str[i]<=57))   // converting string to integer
       {
          printf("NUmber found");
          temp=makeNode();
          temp->val=str[i];
          temp->next=NULL;

      if(*head==NULL)
        *head=temp;

     else
     {  
         temp2=*head;
          while(temp2->next!=NULL)
              temp2=temp2->next;
           temp2->next=temp;
     }
    }
    }
     printList(*head);

}

//program for allocating memory for new node 

struct node *makeNode()

{
     struct node *newNode=(struct node *)malloc(sizeof(struct node));
     return newNode;
}

Aucun commentaire:

Enregistrer un commentaire