Handle crash looping through aspects of object in vector

52 views Asked by At

I have created a number of 'question' objects and stored them within a vector. I want to loop through the vector and do something at the index if the object contains a certain feature. These are the sort of things I have, and some objects will have a different arrangement of these.

QLabel *titleLabel;
QTextEdit *textEdit;
QLineEdit *lineEdit;
QLabel *commentsLabel;
QTextEdit *commentsEdit;
QLineEdit *option;
QLabel *scaleLabel;
QLabel *label;
QLineEdit *scaleFrom;
QLineEdit *scaleTo;

My code crashes if the object at the index doesn't have the specific thing.

Question *question;

for(int i = 0; i< question_vector.size(); i++){

   question = question_vector[i];

   if(question->scaleFrom)
   {
       qDebug() << question->scaleFrom->text();
   }
    else
   {
       qDebug() << "no";
   }
}

The object at index 0 doesnt have a 'scaleFrom' so my program crashes. How do I handle this and skip over it?

1

There are 1 answers

0
user On BEST ANSWER

You're dereferencing a pointer. It needs to point to a valid memory address. Make it so if your objects don't have something, their pointers are set to NULL or nullptr (C++11), so then you can check whether they are == to null. You can then check whether or not the pointer is null before dereferencing it.

Instead of

qDebug() << question->scaleFrom->text();

you'd have:

if (question != nullptr && question->scaleFrom != nullptr)
    qDebug() << question->scaleFrom->text();