【问题标题】:Segmentation fault in file accessing文件访问中的分段错误
【发布时间】:2012-01-14 14:35:33
【问题描述】:

请问为什么这段代码会导致分段错误。我正在尝试从文本文件中获取输入,但我无法弄清楚问题所在。

using namespace std; 
using namespace cv;

int main()
{
    char str[50];
    FILE *trainfile;
    int k, n, maxval1, maxval2, classnum;
    char dataArray[n][3];

    trainfile = fopen("training.txt", "r+");

    if(trainfile == NULL){
        perror("Cannot open file.\n");
    }else{
        while(!feof(trainfile)){
            fscanf(trainfile, "%s", str);       
        }
    }
    fclose(trainfile);

    return 0;
}

【问题讨论】:

  • 你确定 50 个字符就够了吗?此外,如果 trainfile == NULL,则调用 fclose(NULL)

标签: c file segmentation-fault


【解决方案1】:
int k, n, maxval1, maxval2, classnum;
char dataArray[n][3];

n 未初始化,因此它可以是任何值,因此您的代码具有未定义行为

err...它无论如何都没有使用。

代码中的另一个问题是您的数据缓冲区:

char str[50];

应该足够大以容纳文件的内容,它可能不是并且会导致未定义的行为

【讨论】:

  • str 不需要保存整个文件,通常只保存最长的连续非空白字符序列。如果文件是英文纯文本,大概50就够了。但是有一个段错误,所以文件可能不是。
【解决方案2】:

一个问题是您的缓冲区可能不够大。

你应该先得到文件的大小,然后做一个那个大小的动态缓冲区,最后读取文件。

fseek(trainfile,0,SEEK_END); //Go to end
int size = ftell(trainfile); //Tell offset of end from beginning
char* buffer = malloc(size); //Make a buffer of the right size

fseek(ftrainfile,0,SEEK_SET); //Rewind the file

//Read file here with buffer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-18
    • 2020-02-06
    • 2020-07-12
    • 1970-01-01
    • 2016-02-26
    • 2023-03-03
    • 1970-01-01
    • 2017-04-21
    相关资源
    最近更新 更多