Menu

Potential FP: containerOutOfBounds

2022-12-20
2022-12-20
  • Muhammad Javed

    Muhammad Javed - 2022-12-20

    I have the following scenario:

    // test.cpp
    #include <array>
    #include <cstddef>
    
    template<size_t Size>
    struct Test
    {
        Test(std::array<int, Size> aArray)
        {
            if (Size > 2)
            {
                for(int i = mArray.size() - 2; i >= 0; --i)
                {
                    mArray[i] = mArray[i + 1] * aArray[i + 1];
                }
            }
        }
        std::array<int, Size - 1> mArray;
    };
    
    Test<1> t({0});
    

    Cppcheck gives the following report about this code:

    Checking test.cpp ...
    test.cpp:14:51: error: Out of bounds access in 'aArray[i+1]', if 'aArray' size is 1 and 'i+1' is greater or equal to 1 [containerOutOfBounds]
                    mArray[i] = mArray[i + 1] * aArray[i + 1];
                                                      ^
    test.cpp:12:46: note: Assuming that condition 'i>=0' is not redundant
                for(int i = mArray.size() - 2; i >= 0; --i)
                                                 ^
    test.cpp:14:51: note: Access out of bounds
                    mArray[i] = mArray[i + 1] * aArray[i + 1];
                                                      ^
    

    Cppcheck says that if aArray's size is 1 then the access aArray[i+1] would be out of bounds. However, due to the if condition, that access would never occur in such a scenario.
    Thanks.

     

    Last edit: Muhammad Javed 2022-12-20
  • CHR

    CHR - 2022-12-20

    Thanks for reporting, I have created this ticket: https://trac.cppcheck.net/ticket/11447

     
  • Muhammad Javed

    Muhammad Javed - 2022-12-20

    Thank you so much!

     

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.