2013-10-06 62 views
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; 
} 

而且我的錯誤是...複製文件,但誤差雙倍免費或損壞用C

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

對不起,現在是正確的,但我不undertand。我的失敗在哪裏?

+1

什麼是'bytesLeidos'? – glglgl

+2

調皮有argv [1]等而沒有檢查argc的值 – Bathsheba

+1

也調皮不檢查fopen的結果 –

回答

6

您需要檢查的fopen()函數的返回值0

調用FCLOSE()0的結果您所看到的錯誤。

另外,檢查參數的有效範圍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; 
}