简体   繁体   English

尝试访问向量时出现分段错误-cpp

[英]Segmentation fault when trying to access a vector - cpp

I have written some code in c++. 我已经用C ++编写了一些代码。 It reads in data from a CSV file and then simply prints the second line to the screen: 它从CSV文件中读取数据,然后将第二行简单地打印到屏幕上:

vector<string> readCsvFileContent()
{
    vector<string> buffer;

    try {
        ifstream inputFile;
        string line;

        inputFile.open("Input.csv", static_cast<std::ios::openmode>(std::ios::in) );

        while (getline(inputFile,line)) {
            buffer.push_back(line);
        }

       inputFile.close();
    }
    catch (ifstream::failure e) { 
        cout<<"No file read"<<endl;            
        throw e;
    }

    return buffer;
}

This function is called as follows : 该函数称为:

cout << "reading from file" << endl;
vector<string> inputData = readCsvFileContent();
cout << inputData.size() << endl;
cout << inputData[1] << endl;

When it runs in debug it displays what it should: 当它在调试中运行时,将显示其内容:

[ 50%] Building CXX object src/CMakeFiles/version1.dir/version1.cc.o
Linking CXX executable version1
[ 50%] Built target version1
[100%] Generating House1.csv
reading from file
322274
"2014-07-01 00:00:06",155,0,0,0,NULL,0,0,0,0,NULL
[100%] Built target process_csv

But when I run my code I get: 但是,当我运行代码时,我得到:

reading from file
0
Segmentation fault (core dumped)

You get a segfault because you read beyond the vectors borders 您会遇到段错误,因为您阅读的向量边界之外

inputData.size() // 0 i.e. empty
inputData[1] // undefined behaviour

Your code should check whether a file was opened succesfully. 您的代码应检查文件是否成功打开。 You can do this: 你可以这样做:

if (!inputFile.is_open())
    // throw or whatever

Or, since you seem to already be prepared for it with a try-catch, as molbdnilo points out, you can ask the stream to throw on failure: 或者,如molbdnilo所指出的那样,由于您似乎已经为尝试捕获做好了准备,因此您可以要求流引发失败:

inputFile.exceptions(std::ifstream::failbit);

To test if the file was empty, just check inputData.size() which you already print, but ignore. 要测试文件是否为空,只需检查已经打印但忽略的inputData.size()

Now, the remaining question is, why does it work in debug but not in release? 现在,剩下的问题是,为什么它不能在调试中工作,而不能在发行版中工作? Well, my crystal ball is out of battery but I can speculate that your builds have different working directories and the file is missing or not readable in the other one. 好吧,我的水晶球没电了,但我可以推测您的构建版本具有不同的工作目录,并且该文件丢失或在另一个文件中不可读。 You haven't told about what your build does but this might be relevant: 您没有告诉您构建的功能,但这可能是相关的:

[100%] Generating House1.csv [100%]正在生成House1.csv

inputFile.open(" Input.csv ", static_cast(std::ios::in) ); inputFile.open(“ Input.csv ”,static_cast(std :: ios :: in));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM