繁体   English   中英

文件格式导致程序崩溃

[英]program crashes due to file format

我正在从usaco尝试这个问题。 当我在使用文件时使用txt文件时,程序运行正常。 但是,对于提交要求,我将格式更改为beads.in和beads.out时程序崩溃。 有什么问题? 这是我的代码:

#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;
}

您确定已经创建了beads.inbeads.out

根据手册页

 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.

可能是在fopen之前未创建beads.in 最好检查一下fopen的状态,使用perror

您提到它与文本文件一起使用。 我猜想beads.in不是文本文件,而是二进制文件。 如果是这样,则fopen ("beads.in", "rb");在上面的建议中使用: fopen ("beads.in", "rb"); fopen ("beads.out", "wb"); 应该管用。 程序会因二进制输入数据而崩溃的原因是,您正在要求fscanf将数据复制到str缓冲区中,直到遇到换行符为止。 beads.in文件很有可能超过400个字符,这将导致缓冲区溢出并开始覆盖程序堆栈。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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