简体   繁体   中英

Segmentation fault when trying to access a vector - cpp

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)

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) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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