复制文件,但错误双重免费或C中的损坏

时间:2013-10-06 19:30:43

标签: c gcc

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 ***

对不起,现在是对的,但我没有承诺。我的失败在哪里?

1 个答案:

答案 0 :(得分: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;
}