且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

分段错误(核心转储)从标准输入读取

更新时间:2022-02-07 00:34:25

问题是

int main (int argc, char *argv[]) {
    FILE * fp;

    if ( argc != 3 )
    {
            fgets(sentence,sizeof(sentence),stdin);
            // and so on
    }
    else
    {
            fp = fopen( argv[2], "r" );
            if ( fp == 0 )
            {
                    printf( "Could not open file\n" );
            }
            while (readFile(fp, word, size)) {
                    get_word(word);
            }
    }

    // do some stuff, sorting etc.

    fclose(fp);

FCLOSE(FP)不管它是否被打开了。如果 FP 没有连接到一个有效的流,分段错误是常见的。显然,一些实现处理 NULL 参数 FCLOSE 摆好,而这正是它似乎在Mac上运行。

that you fclose(fp) regardless of whether it was opened. If fp is not connected to a valid stream, a segmentation fault is common. Apparently some implementations handle a NULL argument to fclose gracefully, and that's what makes it appear to work on Mac.

移动 FCLOSE 调入其他分公司,并在的fopen 失败,不只是

Move the fclose call into the else branch, and when fopen fails, don't just

printf( "Could not open file\n" );

但结束程序。