使用fopen时的Segfault

nor*_*ter 3 c fopen segmentation-fault

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

FILE *output = NULL;
output = fopen("./output2.txt", "w+");
Run Code Online (Sandbox Code Playgroud)

我不认为它是某种腐败的内存错误,因为当我将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); 
Run Code Online (Sandbox Code Playgroud)

}

lur*_*ker 5

错误实际上是fprintf你的第一个错误fopen.

fprintf(output, "%s", *header);  //output the same header
Run Code Online (Sandbox Code Playgroud)

%s格式说明需要一个char *和你传递一个char值(*header),它试图解释为一个地址,并引起了段错误.

  • @ user2489837:未定义的行为就是这样. (2认同)