Menu

False positive: Array index out of bounds

Andrew
2022-08-20
2022-08-21
  • Andrew

    Andrew - 2022-08-20

    I'd appreciate if someone would look into this warning and raise a ticket if appropriate.

    It looks to be a bug to me give a trivial change in the code avoids it (see comments below).

    #include <string>
    
    int main()
    {
        std::string line("1#2#3#4#5#6#");
        size_t cols[] = { 2, 3, 4 };
        size_t idx = 0, col = 0;
        for (size_t pos = 0; pos != line.size(); ++pos)
        {
            if (line[pos] == '#')
            {
                if (++col == cols[idx])
                {
                    ++idx;
                    // CWE: 788
                    // Either the condition 'idx==sizeof(cols)' is redundant or the array 'cols[3]' is accessed at index 23, which is out of bounds.
                    // but no error if ++idx used inside of if statement
                    if (idx == sizeof(cols))
                        break;
                }
            }
        }
        return 0;
    }
    
     
  • Paul Fultz

    Paul Fultz - 2022-08-20

    It looks like a true positive to me. If ++idx is equal to sizeof(cols)(which is 24) then idx on the previous line if (++col == cols[idx]) would be 23 which is out of bounds since the array has only 3 elements.

    We could probably improve our analysis to detect this error when doing if (++idx == sizeof(cols)) as well.

     
  • Andrew

    Andrew - 2022-08-21

    Darn you're right - thanks for the feedback.

    I guess even after reducing it to a simpler example, I just too focussed on the problem to see that it was using sizeof instead of std::size.

     

    Last edit: Andrew 2022-08-21

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.