noel sean noel sean - 15 days ago 5
C Question

How to get rid of this segmentation error?

void search(FILE *fp){
char lines[81];
char iden[11];


int i = 0;
int count = 1;
while(!feof(fp)){
fgets(lines,80,fp);
// If the line dosesn't start with #, space, or tab, it has identifier
if (lines[0] != '#' && lines[0] != ' ' && lines[0] != '\t'){
// An identifier ends with ':'
while (lines[i] != ':'){
iden[i] = lines[i];
++i;
}
ins(iden, count);
}
++count;
}
}


I am getting an error like this:

p4.c:93:12: runtime error: index 11 out of bounds for type 'char [11]'

p4.c:92:17: runtime error: index 81 out of bounds for type 'char [81]'

p4.c:93:22: runtime error: index 81 out of bounds for type 'char [81]'

Segmentation fault

Note: My input file contains data according to error checks above. I mean each line as at most 80 characters including \n and the max size of an identifier is 10. And lines that doesn't start with '#' or space or tab contains an identifier at the begining of the line that ends with ':' with maximum size of 10 including ':'

It is happening in the second while loop on the above code?
Why am I getting this error?

p.s: I already opened my file and checked it in my main method

Answer

You never reset the counter i and don't add a terminator to the identifier.

So try:

i=0;
while (lines[i] != ':'){
     iden[i] = lines[i];
     ++i;
 }
 iden[i]='\0';

But for safety you should put in protection so actually use:

while (lines[i] != ':' && i<10){

Never trust input and always make sure your program will never exceed bounds of its variables.

Comments