-1

I am trying to traverse link list before inserting values into it.Simply i am trying to insert unique values. please have a look to my code. When i ran my code in GCC compiler it gave segmentation fault

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct link 
{
char name[14];
int data;
struct link *next;
}*start=NULL,*end=NULL,*tem=NULL;


void add(char nam[22])
{
struct link *temp;
temp=(struct link*)malloc(sizeof(struct link));
printf("Enter the data\n");
scanf("%d",&temp->data);
strcpy(temp->name,nam);
temp->next=NULL;
printf("\nadded\n");
if (start==NULL)
{
start=temp;
tem=start;
end=temp;
}
else
{
end->next=temp;
end=temp;
}


}

int traverse(char nam[22])
{
if(tem!=NULL){do
{
if(strcmp(tem->name,nam)==0)
{return 1;}
tem=tem->next;
}while(tem->next!=NULL);
}

return 0;
}

int main()
{
if(traverse("aaa")==0)
add("aaa");
else
printf("already present");

if(traverse("aaa")!=0)
printf("already present");
else
printf("not present ");//add("ashish");

if(traverse("bbb")!=0)
printf("already present");
else
printf("not present ");//add("bishnu");

return 0;
}
Bishnu
  • 383
  • 4
  • 14

1 Answers1

1
int traverse(char nam[22])
{
if(tem!=NULL){do
{
    if(strcmp(tem->name,nam)==0)
    {return 1;}
    tem=tem->next;
    }while(tem->next!=NULL);//this is error. You did not test tem==NULL after previos row
}

return 0;
}