2014-03-07 65 views
2

我從下面的代碼的第二行接收段錯誤:段錯誤而使用的fopen

FILE *output = NULL; 
output = fopen("./output2.txt", "w+"); 

我不認爲這是某種形式的破壞內存錯誤的,因爲當我改變w +來河它運行時沒有段錯誤。此外,它似乎創建該文件之前它segfaults。

編輯:原來mrbatch是正確

我所有的代碼以供參考:

void writeFile(const char *header, int numRows, int numCols, int **grades, const char *outFile) 
{ 
    printf("writefile success\n"); 
    int i, j; 
    FILE *output = NULL; 
    output = fopen("./output2.txt", "w+"); // ERROR HERE (I was wrong, keep reading) 
    printf("testestestsetsete\n\n\n"); //based off the commenters, this code 
              //IS reached but is never printed 

    fprintf(output, "%s", *header); //commenters stated error is here 
            //*header should be header 
    fprintf(output, "%d %d\n", numRows, numCols); //output the number or rows and columns at the second line 

    //output each grades(scores) in the processed 2D array grades 
    for(i = 0; i < numRows; i ++) { //loop through all rows 
     for(j = 0; j < numCols; j ++) //loop through all columns in the i row 
     { 
      if(j < numCols - 1) 
       fprintf(output, "%d ", grades[i][j]); 
      else 
       fprintf(output, "%d\n", grades[i][j]); 
      //printf("\"%d\" ", score); 
     } 
     //printf("\n"); 
    } 

    fclose(output); 

}

+0

錯誤實際上是您的'fopen'之後的第一個'fprintf'。 '%s'格式說明符需要一個'char *',並且你傳遞了一個'char'值('* header'),它試圖將其解釋爲一個地址並導致段錯誤。 – lurker

+0

我知道這不是因爲我在代碼中有一個測試printf(我在發佈之前刪除了它),這是在fopen之後和fprintf之前的。 –

+1

請用'printf'顯示測試代碼並重新運行測試。 'fopen'很好,但是'fprintf'最明顯的不是。或者更好的是,註釋掉'fopen'後面的'fprintf',看看會發生什麼。 – lurker

回答

5

錯誤實際上是第一個fprintf是你fopen後。

fprintf(output, "%s", *header); //output the same header 

%s格式說明需要一個char *,你通過了char值(*header),它試圖解釋爲一個地址,並引起了段錯誤。

+0

啊哈,原來你是對的。但是,這是如何工作的。我有一個測試printf,fopen和fprintf之間從來沒有達到過。 fprintf如何在沒有打我的測試代碼的情況下進行段錯誤? –

+0

@ user2489837看到我上面的評論。 'printf'可能被執行,但輸出還沒有被寫入。 –

+2

@ user2489837:未定義的行爲就是這樣。 – dreamlax