使用fopen时出现段错误

4

我在以下代码的第二行收到了一个段错误(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),它试图将其解释为地址并导致了段错误。 - lurker
1
请展示带有 printf 的测试代码并重新运行测试。fopen 是正常的,但是其后紧随的 fprintf 明显不行。更好的做法是注释掉 fopen 后面的 fprintf 并查看会发生什么。 - lurker
4
在调试类似这种段错误时,使用printf通常是一个不好的工具(作为“是否到达”指示器)。很有可能printf本身已经执行了,但输出在段错误发生(下一行)之前尚未被写入终端,并终止了进程。在调用printf和输出实际显示之间会进行大量缓冲处理。 - Jonathon Reinhart
2
只要(a)以换行符结束消息并且(b)不将输出重定向到文件或管道,使用printf()是可以的。您还可以在printf()后面跟随fflush(stdout)来刷新挂起的输出。 - Jonathan Leffler
@user2489837:我并不认为使用printf语句进行调试一定是不好的 - 你只需要了解它的局限性即可。虽然我实际上会期望printf()调用中的换行符在崩溃之前强制刷新,因为如果它连接到控制台,stdout不应该是完全缓冲的。 - Michael Burr
显示剩余3条评论
1个回答

5
错误实际上发生在你的fopen之后第一个fprintf
fprintf(output, "%s", *header);  //output the same header
< p > %s 格式说明符期望一个 char *,而您传递了一个 char 值 (*header),它试图将其解释为地址并导致了段错误。


啊哈,原来你是对的。但是这是怎么回事呢?我有一个测试 printf,在 fopen 和 fprintf 之间从未被执行。那么 fprintf 怎么会在没有触发我的测试代码的情况下导致段错误呢? - north.mister
@user2489837 请看我上面的评论。printf 可能已经执行了,但输出还没有被写入。 - Jonathon Reinhart
2
@user2489837:未定义行为就是这样。 - dreamlax

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接