使用 fopen 时出现段错误 [英] Segfault while using fopen
本文介绍了使用 fopen 时出现段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从以下代码的第二行收到一个段错误:
I am receiving a segfault from the second line of the following code:
FILE *output = NULL;
output = fopen("./output2.txt", "w+");
我不认为这是某种损坏的内存错误,因为当我将 w+ 更改为 r 时.它运行时没有段错误.此外,它似乎是在出现段错误之前创建文件.
I don't think it is some sort of corrupt memory error because when I change w+ to r. It runs with no segfault. ALSO, it appears to create the file right before it segfaults.
结果 mrbatch 是对的
turns out mrbatch is right
我所有的代码供参考:
void writeFile(const char *header, int numRows, int numCols, int **grades, const char *outFile)
{
printf("writefile success
");
int i, j;
FILE *output = NULL;
output = fopen("./output2.txt", "w+"); // ERROR HERE (I was wrong, keep reading)
printf("testestestsetsete
"); //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
", 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
", grades[i][j]);
//printf(""%d" ", score);
}
//printf("
");
}
fclose(output);
}
推荐答案
错误其实是你的fopen
之后的第一个fprintf
.
The error is actually the first fprintf
after your fopen
.
fprintf(output, "%s", *header); //output the same header
%s
格式说明符需要 char *
并且您传递了 char
值(*header
)它试图将其解释为地址并导致段错误.
The %s
format specifier expects a char *
and you passed a char
value (*header
) which it tried to interpret as an address and caused a segfault.
这篇关于使用 fopen 时出现段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文