使用fopen时出现段错误 [英] Segfault while using fopen

查看:273
本文介绍了使用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\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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆