Segmentation fault while saving data into QVector
-
Hello everyone, I'm very new to Data structures introduced in the Qt. This might be a silly error but I've read a lot of documentation and codes from the people, still I couldn't figure this out. I'm using QCustomPlot library for plotting graphs and QCustomPlot's
setData
function needs Qvector<double> as argument for X & Y axes data. Here is my code snippet:QFile file("MOCK_DATA.txt"); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QVector<double> x(1000), y(1000); QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine();// read first line and so on qDebug() << line; QStringList fields = line.split(',');// split the string /* qDebug() << fields; qDebug()<<fields.at(0).toDouble(); qDebug()<<fields.at(1).toDouble(); */ x.append(fields.at(0).toDouble()); y.append(fields.at(1).toDouble()) }
The MOCK_DATA.txt file is some random populated numbers for X & Y like following:
21 32 23 35 67 89 23 56 12 45 12 34
The output is like this:
./QtData2QCP_test "21 32" ("21 32") 0 Segmentation fault
From the output, its clear that the
line.split
function isn't working as it should but I'm not sure how to do it. -
Your data is separated by space but you are splitting by comma! So,
line.split()
returns a single element.To fix, use:
line.split(" ")
instead.Also, whenever you have a problem like this, you can run the app in debug mode and it will show you exactly the place it crashes at.
-
@Ketank16
Hi. no need to feel stupid. It's an honest mistake.
When you are using Qt containers like QVector
its good with small sanity checks to avoid crashing.like in your case.
QStringList fields = line.split(',');// split the string
if ( fields.size() < 2 ) {
qDebug() << "format error";
return; ( or continue to skip the line)
}
we know we should get 2 entries so we check we at least have that as else
the statement
fields.at(1) will make you crash as it has no item there.This also help if later say the file is damaged or you allow user to load their own.
Then some small sanity check helps to not crash and also more easy see what is going on.