getc函数产生段错误

mrg*_*mrg 0 c unix linux pointers

程序:

#include<stdio.h>
#include<string.h>

char *f_gets(char *s, int n, FILE *iop)
{
    int c=0;
    char *cs;
    cs = s;

    while (--n > 0 && (c = getc(iop)) != EOF)
    {
        if ((*cs++ = c) == '\n')
            break;
    }
    *cs = '\0';
    return (c == EOF && cs == s) ? NULL : s;
}


main(int argc, char *argv[])
{
    FILE *fp1,*fp2;
    char s2[100],s1[100];
    if (argc <= 2 )
        printf("2 argument needed \n"); 
    else
        if((fp1=fopen(argv[1],"r"))== NULL && (fp2=fopen(argv[2],"r"))==NULL)
            printf("cat: can't open The file\n");
        else
        {
            while(1)
            {
                f_gets(s1,100,fp1); // 1st iteration
                f_gets(s2,100,fp2); // 2nd iteration
                if(!strcmp(s1,s2)) 
                    printf("%s %s",s1,s2);
            }
            fclose(fp1);
            fclose(fp2);
        }
}
Run Code Online (Sandbox Code Playgroud)

输出:

$ ./a.out a b
Segmentation fault (core dumped)
$ 
Run Code Online (Sandbox Code Playgroud)

在上面的程序中,当我们第二次调用f_gets时会发生段错误.即使我两次检查程序,也很难找到问题.有没有人解释为什么它会产生问题.

das*_*ght 8

您拨打电话时第二个文件未打开.

问题是你fopen从短路路径呼叫:

if((fp1=fopen(argv[1],"r"))== NULL && (fp2=fopen(argv[2],"r"))==NULL)
Run Code Online (Sandbox Code Playgroud)

由于代码中的错误,当fp1打开正常时,fp2将始终保持关闭状态.这是因为(fp1=fopen(argv[1],"r"))== NULL将评估0,并确保(fp2=fopen(argv[2],"r"))==NULL永远不会被调用.

你可以通过替换解决这个问题&&||,但更好的方法是在同一时间内打开一个文件.