0

I've a 'C' program which has encountered a strange problem.. I'm getting segmentation fault in the line containing "feof(fp)".. I am trying to run on linux..

I even used gdb command to backtrace the program.. But it was of no use..

Check my sample code..

char buf[2000],str[15],lno[5],def[15],ref[15],tmp[15],ch,ifile[20],ofile[20];

int i,j,oldi,count,c,r,d,f,t,lc=0;



FILE *fp=NULL,*fpo=NULL;

void xyzstart()
{
/*
*Some operation that is not at all concerned with the file
*
*/
}

int main()

{

printf("Enter the name of the input file\n");

gets(ifile);



fp=fopen(ifile,"r");
if(fp==NULL)

{

printf("Error");

exit(0);

}



printf("Enter the name of the output file\n");
gets(ofile);

fpo=fopen(ofile,"w");


if(fpo==NULL)

{

printf("Output file couldn't be opened\n");

exit(0);

}




while(!feof(fp))

{

fgets(buf,sizeof(buf),fp);

count++;  //Count the number of lines in a file

}



rewind(fp); //move the file pointer to the beginning of the file



while(!feof(fp)) //Error is here!! Segmentation fault (Core Dumped)!!

{

clear();  //User defined function which clears all the memory

if(count==lc)

{

nodef();  //User defined function which doesn't reads from or writes into a file

noref();  //User defined function which doesn't reads from or writes into a file

print();  //User defined function which writes the values to output file

break;

}



fgets(buf,sizeof(buf),fp); 

{

i=0;

lc++;


    while(buf[i]!=' ') //read until it encounters a space..

      {

      lno[i]=buf[i];

      i++;

      }

    lno[i]='\0';

//puts(lno);///

    }



i++;

oldi=i;

ch=buf[i];

switch(ch)

{

case 'x': xyzstart(); break;

default: printf("Nothing found");
}

}



fclose(fpo);

fclose(fp);

return 0;

}

I really don't know what to do!! Can anyone please help me out?? Thanks in advance!

Here's the code for both clear and xyzstart() void clear()

{

memset(buf,'\0',sizeof(buf));

memset(lno,'\0',sizeof(lno));

memset(def,'\0',sizeof(def));

memset(ref,'\0',sizeof(ref));

i=oldi=0;

memset(str,'\0',sizeof(str));

}

void xyzstart()

{

r=d=c=0;

for(;;c++,i++)

       {

           if(buf[i]==' ')

           break;

           if(buf[i]=='(') break;

           if(buf[i]==';')break;

           if(buf[i]=='\n') break;

           if(buf[i]=='=') break;

           if(buf[i]=='+' || buf[i]=='-') break;

           str[c]=buf[i];

        }

        str[c]='\0';

if(buf[i]=='=')

           assignment();

else if(buf[i]=='+' || buf[i]=='-') //Increments or decrements

            incdec();

          else if(buf[i]=='(')

                udefined();

}
2
  • Are you sure that your file names are less than 19 characters long? If they're not, you'll get a buffer overflow. Jun 6, 2011 at 17:13
  • You're using feof wrong. The feof function does not detect if the next read will fail because the file is at its end; it tests if the last failure was due to the file being at its end. And you are using it without a failure
    – pmg
    Jun 6, 2011 at 17:41

3 Answers 3

3

My guess is that one of the functions called in the while are trashing the file pointer (perhaps closing it).

Main suspects: clear and xyzstart.

4
  • +1: indeed. And the way to debug it is either to use something like Valgrind, or to remove stuff from the loop until it no longer seg-faults. Jun 6, 2011 at 17:14
  • Hey no.. Actually the input file is nowhere used in those functions!!
    – abk07
    Jun 6, 2011 at 17:15
  • 1
    @cnicutar: rewind is a library function :)
    – pmg
    Jun 6, 2011 at 17:38
  • @pmg :"> I am ashamed and amazed. In my defense I always used fseek :">
    – cnicutar
    Jun 6, 2011 at 17:39
2

Some notes:

  1. Do not use feof(fp) as your while loop condition; the function will only return true after you try to read past the end of the file, so you'll wind up looping once too often. Check the result of your input operation (fgets will return NULL on failure) and then test for EOF, like so:

    
    while(fgets(buf, sizeof buf, fp) != NULL)
      count++;
    if (feof(fp))
      printf("At end of file\n");
    

  2. NEVER NEVER NEVER NEVER NEVER use gets: it will introduce a point of failure in your program (and probably has in this case). It has been deprecated as of C99 and is expected to be gone from the next version of the language (yes, the mayhem caused by this one library call is scarier than the prospect of breaking over 30 years of legacy code). Use fgets or some other alternative instead.

From the code you've posted, I see no obvious issues; I don't know why feof would core dump if the previous statement was a successful rewind. The only thing I can figure is that the file pointer is being overwritten somewhere (possibly by a buffer overrun in a gets call).

3
  • 1
    gets() is removed in the current draft of the C201x standard.
    – pmg
    Jun 6, 2011 at 17:48
  • Hey thanks for the reply! I'm modifying the code now. I'll let you know the result in a couple of minutes..
    – abk07
    Jun 6, 2011 at 18:07
  • Hey I made the following changes to my code.. 1) Used scanf to read the file name 2) Used checked for feof as suggested by John.. 3) Used fseek instead of rewind 4) Used fgets as suggested by John!! And it worked!! Thanks!! :)
    – abk07
    Jun 7, 2011 at 17:47
1
  1. what actually "clear" doing?
  2. this loop looks dangerous:

    while(buf[i]!=' ') //read until it encounters a space..

what if buf doesn't contain spaces?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.