0
int main(int argc, char **argv)
{
    FILE *fe, *fs;
    unsigned char buffer[2048]; 
    int bytesreader;

    fe = fopen(argv[1], "rb"); 

    fs = fopen(argv[2], "wb"); 


    while((bytesreader = fread(buffer, 1, 2048, fe)))
       fwrite(buffer, 1, bytesreader, fs);

    fclose(fe);
    fclose(fs);
    return 0;
}

而我的错误是......

*** glibc detected *** ./doc2: double free or corruption (top): 0x096b7008 ***

对不起,现在是正确的,但我不明白。我的失败在哪里?

4

1 回答 1

6

您需要检查 fopen() 的返回值是否为 0。

在 0 上调用 fclose() 会导致您看到的错误。

此外,检查 argc 以获取有效的参数范围。

int main(int argc, char **argv)
{
    FILE *fe, *fs;
    unsigned char buffer[2048]; 
    int bytesreader;

    if(argc != 3) {
        fprintf(stderr, "usage: %s file1 file2\n", argv[0]);
        exit(1);
    }

    fe = fopen(argv[1], "rb"); 
    if(fe == 0) {
        fprintf(stderr, "%s: Failed to open %s for read\n", argv[0], argv[1]);
        exit(1);
    }

    fs = fopen(argv[2], "wb"); 
    if(fs == 0) {
        fprintf(stderr, "%s: Failed to open %s for write\n", argv[0], argv[2]);
        exit(1);
    }


    while((bytesreader = fread(buffer, 1, 2048, fe)))
       fwrite(buffer, 1, bytesreader, fs);

    fclose(fe);
    fclose(fs);
    return 0;
}
于 2013-10-06T19:33:18.003 回答