我在以下代码的第二行收到了一个段错误(segfault):
FILE *output = NULL;
output = fopen("./output2.txt", "w+");
我认为这不是某种内存错误,因为当我将"w+"更改为"r"时,它可以正常运行而没有段错误。此外,在它出现段错误之前,似乎已经成功创建了该文件。
编辑:事实证明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);
}
fopen
之后的第一个fprintf
。%s
格式说明符期望一个char *
,而您传递了一个char
值 (*header
),它试图将其解释为地址并导致了段错误。 - lurkerprintf
的测试代码并重新运行测试。fopen
是正常的,但是其后紧随的fprintf
明显不行。更好的做法是注释掉fopen
后面的fprintf
并查看会发生什么。 - lurkerprintf
通常是一个不好的工具(作为“是否到达”指示器)。很有可能printf
本身已经执行了,但输出在段错误发生(下一行)之前尚未被写入终端,并终止了进程。在调用printf
和输出实际显示之间会进行大量缓冲处理。 - Jonathon Reinhartprintf()
是可以的。您还可以在printf()
后面跟随fflush(stdout)
来刷新挂起的输出。 - Jonathan Lefflerprintf()
调用中的换行符在崩溃之前强制刷新,因为如果它连接到控制台,stdout
不应该是完全缓冲的。 - Michael Burr