使用fopen时的Segfault

时间:2014-03-07 03:26:40

标签: c segmentation-fault fopen

我从以下代码的第二行收到段错误:

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

我认为这不是某种腐败的内存错误,因为当我将w +更改为r时。它运行时没有段错误。此外,它似乎在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); 

}

1 个答案:

答案 0 :(得分:5)

错误实际上是fprintf之后的第一个fopen

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

%s格式说明符需要char *并且您传递了char值(*header),它试图将其解释为地址并导致段错误。