我正在从以下代码的第二行接收segfault:
FILE *output = NULL;
output = fopen("./output2.txt", "w+");
我不认为这是某种损坏的内存错误,因为当我将W 更改为R时。它在没有segfault的情况下运行。另外,它似乎在segfaults之前就创建了文件。
编辑:事实证明MRBatch是正确的
我所有的代码供参考:
void writeFile(const char *header, int numRows, int numCols, int **grades, const char *outFile)
{
printf("writefile successn");
int i, j;
FILE *output = NULL;
output = fopen("./output2.txt", "w+"); // ERROR HERE (I was wrong, keep reading)
printf("testestestsetsetennn"); //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 %dn", 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, "%dn", grades[i][j]);
//printf(""%d" ", score);
}
//printf("n");
}
fclose(output);
}
错误实际上是您fopen
之后的第一个fprintf
。
fprintf(output, "%s", *header); //output the same header
%s
格式指定器期望char *
,您通过了char
值(*header
),它试图将其解释为地址并引起segfault。