Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. operator[]:"index out of range"
Forum Update on Monday, May 27th 2025

operator[]:"index out of range"

Scheduled Pinned Locked Moved Unsolved General and Desktop
19 Posts 7 Posters 1.7k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    Swathika
    wrote on last edited by
    #1

    Re: ASSERT failure in QList<T>::operator[]: "index out of range"

    SAVE_20230505_093115.jpg

    Get an error can anyone help me out with this?

    C 1 Reply Last reply
    0
    • S Swathika

      Re: ASSERT failure in QList<T>::operator[]: "index out of range"

      SAVE_20230505_093115.jpg

      Get an error can anyone help me out with this?

      C Offline
      C Offline
      ChrisW67
      wrote on last edited by
      #2

      @Swathika The only line of code I can see in the screen photo (?) that might trigger this message is the first visible one. This will fail if the rootObjects() list is empty, i.e. it does not contain an element at index 0. No idea if that is where your program fails though.

      Run your program in the debugger until it ASSERTS then copy and paste the text of the stack backtrace here.

      1 Reply Last reply
      1
      • S Offline
        S Offline
        Swathika
        wrote on last edited by
        #3

        In the 34th line I'm getting the error

        1 Reply Last reply
        0
        • jeremy_kJ Offline
          jeremy_kJ Offline
          jeremy_k
          wrote on last edited by
          #4

          Please post code as text using code tags (</> in the formatting tools bar), not a screen shot or other image capture.

          Asking a question about code? http://eel.is/iso-c++/testcase/

          Christian EhrlicherC 1 Reply Last reply
          1
          • jeremy_kJ jeremy_k

            Please post code as text using code tags (</> in the formatting tools bar), not a screen shot or other image capture.

            Christian EhrlicherC Offline
            Christian EhrlicherC Offline
            Christian Ehrlicher
            Lifetime Qt Champion
            wrote on last edited by
            #5

            val is a temporary and therefore invalid inside your lambda function.

            Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
            Visit the Qt Academy at https://academy.qt.io/catalog

            jeremy_kJ 1 Reply Last reply
            1
            • S Offline
              S Offline
              Swathika
              wrote on last edited by
              #6

              #include <QGuiApplication>
              #include <QQmlApplicationEngine>
              #include <QTimer>

              #include "speedometer.h"

              #include <unistd.h>

              int main(int argc, char *argv[])
              {
              #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
              QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
              #endif
              QGuiApplication app(argc, argv);

              qmlRegisterType<Speedometer>("com.sample.speedometer",1,0,"Speedometer");
              
              QQmlApplicationEngine engine;
              const QUrl url(QStringLiteral("qrc:/main.qml"));
              
              QObject * object = engine.rootObjects()[0];
              QObject *speedometer= object->findChild<QObject*>("speedoMeter");
              
                  Speedometer *ptrSpeedometer=qobject_cast<Speedometer*>(speedometer);
              
                  qreal val=0;
                  ptrSpeedometer->setSpeed(val);
              
                  QTimer timer1;
              
                      QObject::connect(&timer1,&QTimer::timeout,[&] ()
                       {
                         val = val + 10;
                         ptrSpeedometer->setSpeed(val);
                      });
              
                      timer1.start(100);
              
              
              QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                               &app, [url](QObject *obj, const QUrl &objUrl) {
                  if (!obj && url == objUrl)
                      QCoreApplication::exit(-1);
              }, Qt::QueuedConnection);
              engine.load(url);
              
              return app.exec();
              

              }

              JonBJ 1 Reply Last reply
              0
              • S Swathika

                #include <QGuiApplication>
                #include <QQmlApplicationEngine>
                #include <QTimer>

                #include "speedometer.h"

                #include <unistd.h>

                int main(int argc, char *argv[])
                {
                #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
                QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
                #endif
                QGuiApplication app(argc, argv);

                qmlRegisterType<Speedometer>("com.sample.speedometer",1,0,"Speedometer");
                
                QQmlApplicationEngine engine;
                const QUrl url(QStringLiteral("qrc:/main.qml"));
                
                QObject * object = engine.rootObjects()[0];
                QObject *speedometer= object->findChild<QObject*>("speedoMeter");
                
                    Speedometer *ptrSpeedometer=qobject_cast<Speedometer*>(speedometer);
                
                    qreal val=0;
                    ptrSpeedometer->setSpeed(val);
                
                    QTimer timer1;
                
                        QObject::connect(&timer1,&QTimer::timeout,[&] ()
                         {
                           val = val + 10;
                           ptrSpeedometer->setSpeed(val);
                        });
                
                        timer1.start(100);
                
                
                QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                                 &app, [url](QObject *obj, const QUrl &objUrl) {
                    if (!obj && url == objUrl)
                        QCoreApplication::exit(-1);
                }, Qt::QueuedConnection);
                engine.load(url);
                
                return app.exec();
                

                }

                JonBJ Offline
                JonBJ Offline
                JonB
                wrote on last edited by JonB
                #7

                @Swathika
                Please take the time to put code blocks inside the forum's Code tags, it's not hard to do.

                You use the result of findChild<QObject*>("speedoMeter") and qobject_cast<Speedometer*>(speedometer) without ever checking whether it is nullptr. You should always check, especially if you have unexpected behaviour like now.

                @ChrisW67 told you what you need to do

                Run your program in the debugger until it ASSERTS then copy and paste the text of the stack backtrace here.

                @Swathika

                In the 34th line I'm getting the error

                Would you care to tell us which line is number 34 --- especially since the code block is not properly tagged --- or do you think it's preferable people should have to count in order to help with your issue?

                C 1 Reply Last reply
                0
                • Christian EhrlicherC Christian Ehrlicher

                  val is a temporary and therefore invalid inside your lambda function.

                  jeremy_kJ Offline
                  jeremy_kJ Offline
                  jeremy_k
                  wrote on last edited by
                  #8

                  @Christian-Ehrlicher said in operator[]:"index out of range":

                  val is a temporary and therefore invalid inside your lambda function.

                  I agree with the sentiment. Don't capture an auto scoped variable by reference.

                  I'm skeptical that this is the issue here. timer1 is auto scoped to the same function, and declared after val.

                  Asking a question about code? http://eel.is/iso-c++/testcase/

                  JonBJ Christian EhrlicherC 2 Replies Last reply
                  0
                  • jeremy_kJ jeremy_k

                    @Christian-Ehrlicher said in operator[]:"index out of range":

                    val is a temporary and therefore invalid inside your lambda function.

                    I agree with the sentiment. Don't capture an auto scoped variable by reference.

                    I'm skeptical that this is the issue here. timer1 is auto scoped to the same function, and declared after val.

                    JonBJ Offline
                    JonBJ Offline
                    JonB
                    wrote on last edited by JonB
                    #9

                    @jeremy_k , @Christian-Ehrlicher
                    But neither of these is the issue here, since [we now know, but did not from the photograph] they are local variables in main() which persists/lives across the lifetime on the signal connection.

                    The assertion is on a QList<T>::operator[]. It is not yet clear where this would be involved. That is why we still await the stack trace from the OP.

                    1 Reply Last reply
                    0
                    • jeremy_kJ jeremy_k

                      @Christian-Ehrlicher said in operator[]:"index out of range":

                      val is a temporary and therefore invalid inside your lambda function.

                      I agree with the sentiment. Don't capture an auto scoped variable by reference.

                      I'm skeptical that this is the issue here. timer1 is auto scoped to the same function, and declared after val.

                      Christian EhrlicherC Offline
                      Christian EhrlicherC Offline
                      Christian Ehrlicher
                      Lifetime Qt Champion
                      wrote on last edited by
                      #10

                      @jeremy_k said in operator[]:"index out of range":

                      agree with the sentiment. Don't capture an auto scoped variable by reference.
                      I'm skeptical that this is the issue here. timer1 is auto scoped to the same function, and declared after val.

                      This does not matter - but as @JonB pointed out it's not inside a function but inside main() so val is still alive. Even though the design is crappy.

                      Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                      Visit the Qt Academy at https://academy.qt.io/catalog

                      jeremy_kJ 1 Reply Last reply
                      1
                      • Christian EhrlicherC Christian Ehrlicher

                        @jeremy_k said in operator[]:"index out of range":

                        agree with the sentiment. Don't capture an auto scoped variable by reference.
                        I'm skeptical that this is the issue here. timer1 is auto scoped to the same function, and declared after val.

                        This does not matter - but as @JonB pointed out it's not inside a function but inside main() so val is still alive. Even though the design is crappy.

                        jeremy_kJ Offline
                        jeremy_kJ Offline
                        jeremy_k
                        wrote on last edited by
                        #11

                        @Christian-Ehrlicher said in operator[]:"index out of range":

                        @jeremy_k said in operator[]:"index out of range":
                        it's not inside a function but inside main() so val is still alive. Even though the design is crappy.

                        main() is just another function, with the same auto scoping rules. I think we, including @JonB are all coming to the same conclusion: bad design, but not the issue at hand.

                        Asking a question about code? http://eel.is/iso-c++/testcase/

                        Christian EhrlicherC JonBJ 2 Replies Last reply
                        0
                        • jeremy_kJ jeremy_k

                          @Christian-Ehrlicher said in operator[]:"index out of range":

                          @jeremy_k said in operator[]:"index out of range":
                          it's not inside a function but inside main() so val is still alive. Even though the design is crappy.

                          main() is just another function, with the same auto scoping rules. I think we, including @JonB are all coming to the same conclusion: bad design, but not the issue at hand.

                          Christian EhrlicherC Offline
                          Christian EhrlicherC Offline
                          Christian Ehrlicher
                          Lifetime Qt Champion
                          wrote on last edited by
                          #12

                          @jeremy_k said in operator[]:"index out of range":

                          main() is just another function, with the same auto scoping rules.

                          You did not understood what I've said. val is a danling reference in this case:

                          void ClassFoo::foo()
                          {
                              Speedometer *ptrSpeedometer=qobject_cast<Speedometer*>(speedometer);
                          
                              qreal val=0;
                              ptrSpeedometer->setSpeed(val);
                          
                              QObject::connect(&timer1,&QTimer::timeout,[&] ()
                              {
                                    val = val + 10;
                                    ptrSpeedometer->setSpeed(val);
                              });
                              timer1.start(100);
                          }
                          

                          I never expected such code inside main() so ...

                          Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                          Visit the Qt Academy at https://academy.qt.io/catalog

                          1 Reply Last reply
                          2
                          • jeremy_kJ jeremy_k

                            @Christian-Ehrlicher said in operator[]:"index out of range":

                            @jeremy_k said in operator[]:"index out of range":
                            it's not inside a function but inside main() so val is still alive. Even though the design is crappy.

                            main() is just another function, with the same auto scoping rules. I think we, including @JonB are all coming to the same conclusion: bad design, but not the issue at hand.

                            JonBJ Offline
                            JonBJ Offline
                            JonB
                            wrote on last edited by JonB
                            #13

                            @jeremy_k
                            As @Christian-Ehrlicher writes. Passing a local/auto variable to a lambda as a reference is not in itself any problem. Loads of lambdas may be written which use this, e.g. (I haven't looked) perhaps some of the std:: container algorithms may use reference parameters.

                            The potential problem arises when it is a slot for a signal, because that continues to use the lambda after the function which does the connect() exits. Then a reference parameter to a variable local to the function would indeed be a problem, as @Christian-Ehrlicher's code shows. However, in this particular case the OP is doing it from main(), so that will not be a problem here.

                            jeremy_kJ 1 Reply Last reply
                            2
                            • Paul ColbyP Offline
                              Paul ColbyP Offline
                              Paul Colby
                              wrote on last edited by Paul Colby
                              #14

                              Surely the OP issue is:

                              QQmlApplicationEngine engine;
                              const QUrl url(QStringLiteral("qrc:/main.qml")); ///< You've done nothing with this yet.
                              
                              QObject * object = engine.rootObjects()[0]; ///< rootObjects is empty, 0 is not a valid index.
                              
                              ...
                              
                              engine.load(url); ///< Only now do you add anything to the engine.
                              
                              return app.exec();
                              

                              Presumably you need to call QQmlApplicationEngine::load() earlier, or fetch the first root-object later?

                              Cheers.

                              JonBJ 1 Reply Last reply
                              3
                              • Paul ColbyP Paul Colby

                                Surely the OP issue is:

                                QQmlApplicationEngine engine;
                                const QUrl url(QStringLiteral("qrc:/main.qml")); ///< You've done nothing with this yet.
                                
                                QObject * object = engine.rootObjects()[0]; ///< rootObjects is empty, 0 is not a valid index.
                                
                                ...
                                
                                engine.load(url); ///< Only now do you add anything to the engine.
                                
                                return app.exec();
                                

                                Presumably you need to call QQmlApplicationEngine::load() earlier, or fetch the first root-object later?

                                Cheers.

                                JonBJ Offline
                                JonBJ Offline
                                JonB
                                wrote on last edited by
                                #15

                                @Paul-Colby said in operator[]:"index out of range":

                                QObject * object = engine.rootObjects()[0]; ///< rootObjects is empty, 0 is not a valid index.

                                If this is indeed the cause of the "index out of range", how do you explain the OP's
                                @Swathika said in operator[]:"index out of range":

                                In the 34th line I'm getting the error

                                Which (when he forces us to count) appears to be within the lambda?

                                I don't know anything about QML, what you have said would make perfect sense but not given that line number? Unless we don't trust the OP's reports. Which is why if we were given the stack trace as previously requested we would know for sure! :)

                                C 1 Reply Last reply
                                3
                                • JonBJ JonB

                                  @Paul-Colby said in operator[]:"index out of range":

                                  QObject * object = engine.rootObjects()[0]; ///< rootObjects is empty, 0 is not a valid index.

                                  If this is indeed the cause of the "index out of range", how do you explain the OP's
                                  @Swathika said in operator[]:"index out of range":

                                  In the 34th line I'm getting the error

                                  Which (when he forces us to count) appears to be within the lambda?

                                  I don't know anything about QML, what you have said would make perfect sense but not given that line number? Unless we don't trust the OP's reports. Which is why if we were given the stack trace as previously requested we would know for sure! :)

                                  C Offline
                                  C Offline
                                  CPPUIX
                                  wrote on last edited by CPPUIX
                                  #16

                                  @JonB said in operator[]:"index out of range":

                                  Unless we don't trust the OP's reports.

                                  I trust the error to point the problematic line in this case, there is no operator[] in line 34, but there is one in line 24...maybe just a typo from OP?

                                  JonBJ 1 Reply Last reply
                                  1
                                  • C CPPUIX

                                    @JonB said in operator[]:"index out of range":

                                    Unless we don't trust the OP's reports.

                                    I trust the error to point the problematic line in this case, there is no operator[] in line 34, but there is one in line 24...maybe just a typo from OP?

                                    JonBJ Offline
                                    JonBJ Offline
                                    JonB
                                    wrote on last edited by JonB
                                    #17

                                    @Abderrahmene_Rayene This is why users could take the 10 seconds required to put in qDebug() statements or run under debugger, instead of making readers speculate :)

                                    1 Reply Last reply
                                    2
                                    • JonBJ JonB

                                      @Swathika
                                      Please take the time to put code blocks inside the forum's Code tags, it's not hard to do.

                                      You use the result of findChild<QObject*>("speedoMeter") and qobject_cast<Speedometer*>(speedometer) without ever checking whether it is nullptr. You should always check, especially if you have unexpected behaviour like now.

                                      @ChrisW67 told you what you need to do

                                      Run your program in the debugger until it ASSERTS then copy and paste the text of the stack backtrace here.

                                      @Swathika

                                      In the 34th line I'm getting the error

                                      Would you care to tell us which line is number 34 --- especially since the code block is not properly tagged --- or do you think it's preferable people should have to count in order to help with your issue?

                                      C Offline
                                      C Offline
                                      CPPUIX
                                      wrote on last edited by CPPUIX
                                      #18
                                      This post is deleted!
                                      1 Reply Last reply
                                      0
                                      • JonBJ JonB

                                        @jeremy_k
                                        As @Christian-Ehrlicher writes. Passing a local/auto variable to a lambda as a reference is not in itself any problem. Loads of lambdas may be written which use this, e.g. (I haven't looked) perhaps some of the std:: container algorithms may use reference parameters.

                                        The potential problem arises when it is a slot for a signal, because that continues to use the lambda after the function which does the connect() exits. Then a reference parameter to a variable local to the function would indeed be a problem, as @Christian-Ehrlicher's code shows. However, in this particular case the OP is doing it from main(), so that will not be a problem here.

                                        jeremy_kJ Offline
                                        jeremy_kJ Offline
                                        jeremy_k
                                        wrote on last edited by
                                        #19

                                        @JonB said in operator[]:"index out of range":

                                        @jeremy_k
                                        As @Christian-Ehrlicher writes. Passing a local/auto variable to a lambda as a reference is not in itself any problem. Loads of lambdas may be written which use this, e.g. (I haven't looked) perhaps some of the std:: container algorithms may use reference parameters.

                                        The potential problem arises when it is a slot for a signal, because that continues to use the lambda after the function which does the connect() exits. Then a reference parameter to a variable local to the function would indeed be a problem, as @Christian-Ehrlicher's code shows. However, in this particular case the OP is doing it from main(), so that will not be a problem here.

                                        Yes, I did understand. It appears to be my point that was misunderstood. The code, abbreviated, was:

                                        int main() {
                                            qreal val=0;
                                            QTimer timer1;
                                        
                                                QObject::connect(&timer1,&QTimer::timeout,[&] ()
                                                 {
                                                   val = val + 10;
                                                });
                                        
                                                timer1.start(100);
                                        }
                                        

                                        Given:

                                        • Connections are broken when the object that emits the signal is destroyed.
                                        • timer1 has the same automatic block scope as val. val is declared before timer1, and will therefore be destructed after it.
                                        • There is no evidence of a move operation to alter the lifetime of timer1.

                                        We can determine that the reference to val does not dangle prior to timer1 being destroyed, breaking the connection.

                                        The situation would be the same in any function, or for any code block. main() does not alter the situation.

                                        Asking a question about code? http://eel.is/iso-c++/testcase/

                                        1 Reply Last reply
                                        0

                                        • Login

                                        • Login or register to search.
                                        • First post
                                          Last post
                                        0
                                        • Categories
                                        • Recent
                                        • Tags
                                        • Popular
                                        • Users
                                        • Groups
                                        • Search
                                        • Get Qt Extensions
                                        • Unsolved