Segmentation fault when trying to access a vector - cpp

隐身守侯 提交于 2019-12-13 04:47:46

问题


I have written some code in c++. It reads in data from a CSV file and then simply prints the second line to the screen:

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)

回答1:


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:

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

To test if the file was empty, just check inputData.size() which you already print, but ignore.

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

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



来源:https://stackoverflow.com/questions/28277715/segmentation-fault-when-trying-to-access-a-vector-cpp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!