简体   繁体   中英

program crashes due to file format

i was trying this problem from usaco. when i use txt file while using file the program is working fine. but when for the submission requirement i change the format to beads.in and beads.out the program crashes. what;s the problem? here's my code:

#include <stdio.h>
#include<string.h>
main () {
    FILE *fin  = fopen ("beads.in", "r");
    FILE *fout = fopen ("beads.out", "w");
    int n;
    char str[400];
    char now,rev_now;
    int pos,forward,reverse,sum,max=0,i,j,k;
    fscanf(fin,"%d\n%s",&n,str);
    n--;
    for(pos=0;pos<=n;pos++){
        now=str[pos];
        if(pos==0)k=n;
        else k=pos-1;
        rev_now=str[k];
        forward=2;
        int flag1=0,flag2=0,reverse=2;

        for(i=pos,j=k;;){
            if(i==n)i=-1;
            if((str[i+1]==now||str[i+1]=='w')&&flag1==0){
                i++;
                forward++;
            }
            else{
                flag1=1;
            }
            if(j==0)j=n+1;
            if((str[j-1]==rev_now||str[j-1]=='w')&&flag2==0){
                j++;
                reverse++;
            }
            else{
                flag2=1;
            }
            if(flag1==1 && flag2==1)break;
        }
        sum=forward+reverse;
        if(max<sum){max=sum;}
    }
    fprintf(fout,"%d\n",max);
    return 0;
}

are you sure beads.in and beads.out are created already..

According to man page

 r      Open  text  file  for  reading.  The stream is positioned at the
        beginning of the file.

 w      Truncate  file  to  zero length or create text file for writing.
        The stream is positioned at the beginning of the file.

May be beads.in is not created in prior to fopen. It's better if you check the status of the fopen , use perror .

You mention that it works with a text file. I'm guessing that beads.in is not a text file, but rather a binary file. If that is the case, then @KVD's suggestion above to use: fopen ("beads.in", "rb"); and fopen ("beads.out", "wb"); should work. The reason the program would crash with binary input data is because you are asking fscanf to copy data into your str buffer until it encounters a newline character. More than likely, the beads.in file has more than 400 characters which will cause a buffer overflow and start overwriting the program stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM