noel sean noel sean - 1 year ago 57
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;
// 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];
ins(iden, 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 Source

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

So try:

while (lines[i] != ':'){
     iden[i] = lines[i];

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download