Reputation: 510
I am receiving a segfault from the second line of the following code:
FILE *output = NULL;
output = fopen("./output2.txt", "w+");
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.
EDIT: turns out mrbatch is right
All my code for reference:
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);
}
Upvotes: 4
Views: 13096
Reputation: 58244
The error is actually the first fprintf
after your fopen
.
fprintf(output, "%s", *header); //output the same 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.
Upvotes: 5