Menu

containerOutOfBounds missed check and false-positive in gtest and qt code

2021-09-13
2021-09-15
  • Steve Albright

    Steve Albright - 2021-09-13

    I have failures on the line with the at() calls with a non-zero index that I am not able to give a failure example on but realized that cppcheck also misses a case when the list is empty.

    in my production (test) code I get this error

    error: containerOutOfBounds - Out of bounds access in 'firstEntities.at', if 'firstEntities' size is 1 and '1' is 1

    containerOutOfBounds - Out of bounds access in 'firstEntities.at', if 'firstEntities' size is 1 and '2' is 2

    I put some comments in the code below that demonstrates the miss and hopefully you can find the failure case too.

    #include <QList>
    #include <QSharedPointer>
    #include <QSet>
    #include <QString>
    #include <gtest/gtest.h>
    
    class DummyClass
    {
    public:
       QString GetDummyId() { return QString::number(rand()); }
    };
    
    typedef QSharedPointer<DummyClass> DummyClassPtr;
    
    QList<DummyClassPtr> GetDummyClassList()
    {
       QList<DummyClassPtr> list;
    
       if(rand() % 2)
       {
          // when commented out this list is always empty and there is no cppcheck complaint
    //      list = { QSharedPointer<DummyClass>(new DummyClass()), QSharedPointer<DummyClass>(new DummyClass()), QSharedPointer<DummyClass>(new DummyClass()) };
       }
    
       return list;
    }
    
    void containerOutOfBoundsExample()
    {
       QList<DummyClassPtr> firstEntities { GetDummyClassList() };
    
       // even if you comment out this line, cppcheck passes when the list is empty
       ASSERT_EQ(3, firstEntities.count()); // this ensures we have the size we need but getting false positive below that I can't come up with an example for
    
       QSet<QString> importedEntities { firstEntities.at(0)->GetDummyId(), firstEntities.at(1)->GetDummyId(), firstEntities.at(2)->GetDummyId() };
    
       (void)importedEntities;
    }
    
     

    Last edit: Steve Albright 2021-09-13
  • Daniel Marjamäki

    I have failures on the line with the at() calls with a non-zero index that I am not able to give a failure example on but realized that cppcheck also misses a case when the list is empty.

    Did you try the method to remove piece by piece from your code?

    I put some comments in the code below that demonstrates the miss and hopefully you can find the failure case too.

    sorry but I give up almost instantly. It is very hard to guess. It could be a bug in tokenizer/symboldatabase/valueflow/checker/library/..

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.