Hey,
i've just started studying software engineering and i am having a lot of trouble with a program i wrote for an assignment. the program is just meant to read a file line by line tokenise the line, check it against certain parameters and then print before going onto the next line.
after writing the program i got a segmentation fault, and then used gdb to see what was the problem. It compiles fine.
Gdb returned this:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7ac22ad in fgets () from /lib/libc.so.6
the code is as follows:
Code:
#include <stdio.h>
#include <string.h>
int AR = 100;
char *item;
char line[201]="asdf";
int a;
int isbn[11];
int first[100];
char checked[20];
int main()
{
int i,sum,check,j,k,p;
printf("%-13s %-15s %-10s %-20s\n\n","ISBN Code","Check Digit","Sum","Validation Message");
FILE *fileisbn;
fileisbn = fopen("isbn.txt","r");
int e =0, d=0;
/*while(fscanf(fileisbn,"%s",item))*/
while (fgets(line, 20, fileisbn))
{item=strtok(line,"-");
a = atoi(item);
a=isbn[0];
item=strtok(NULL,"");
a = atoi(item);
a=isbn[1];
item=strtok(NULL,"");
a = atoi(item);
a=isbn[2];
item=strtok(NULL,"");
a = atoi(item);
a=isbn[4];
item=strtok(NULL,"-");
a = atoi(item);
a=isbn[5];
item=strtok(NULL,"");
a = atoi(item);
a=isbn[6];
item=strtok(NULL,"");
a = atoi(item);
a=isbn[7];
item=strtok(NULL,"-");
a = atoi(item);
a=isbn[8];
item=strtok(NULL,"\n");
p=strcmp(item,"x");
if (p=0)
{isbn[9]=10;}
else
a=atoi(item);
a=isbn[9];
for(i=0;i<9;i++)
{sum+=isbn[i]*i;}
check=sum%isbn[9];
if (check=isbn[9])
{strcpy(checked,"Validated");
d++;}
else
strcpy(checked,"Error in ISBN code");
printf("%d-",isbn[0]);
for(j=1;j<=3;j++)
{printf("%d",isbn[j]);}
printf("-");
for(k=4;k<=8;k++)
{printf("%d",isbn[k]);}
if (p=0)
{printf("-x");}
else
printf("-%d",isbn[9]);
printf("%-15d",isbn[9]);
printf("%-10d",sum);
printf("%-20s\n",checked);
e++;
}
printf("Total number of ISBN codes processed = %d",e );
printf("Total number of ISBN codes validated = %d",d);
return;
}
As i only used fgets once it is safe to assume the line in which the error is occuring.