Solved How to catch a QVector "index out of range"
-
Hi,
I'm having some problems with QVector. In my application I use a lot of QVector to display charts and other stuff, but sometimes I got this error and every time I can't catch it.
ASSERT failure in QVector<T>::at: "index out of range", file C:/Qt/5.9.1/mingw53_32/include/QtCore/qvector.h, line 430
Going to line 430 I found this piece of code.
template <typename T> inline const T &QVector<T>::at(int i) const { Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::at", "index out of range"); return d->begin()[i]; }
I'm wondering if it's possible to modify this piece of code above to get something that can help me to catch which QVector is giving the problem and where in the code or anyway something more than just that sentence.
Somebody knows how to get them or somebody has any advice?
Thanks in advance.
-
Just run your code in a debugger. It will catch the exception and you get a stack trace where you can see the place you use the vector with wrong index.
Regards
-
@aha_1980 Thank you for your answer.
You're right but sometimes in a debugger QVectors don't give me error. And I must admit that the debugger engine is so slow and it would be easier if I could get some information just to understand which qvector is giving me the problem.
Do you have others advices?
-
Another possibility I see is to add
Q_ASSERT(index < vector.size());
before every access with [] or at().If index is something you don't have under control, you will need to check it anyway before passing it to Qt.
-
@aha_1980 thank your answer. I will try this option!
-
@aha_1980 said in How to catch a QVector "index out of range":
Q_ASSERT(index < vector.size());
maby
Q_ASSERT(index >= 0 && index < vector.size());
I had an occasion when I wanted to capture the object from QVector according to the QModelIndex row. And when QModelIndex = (-1, -1) we have error index out of range :)
We can avoid it by !QModelIndex::isValid(), but still.