Menu

False Positive arrayOutOfBounds in for loop

2021-04-28
2021-04-30
  • Simon Stark

    Simon Stark - 2021-04-28

    Code-Snippet:

      uint32_t array[16];
      for (uint32_t i = 0UL; i < 16; i += 4)
      {
            array[i] = someRandomValue;
            array[i+1UL] = 0UL;
            array[i+2UL] = 0UL;
            array[i+3UL] = 0UL;
      }
    

    CppChecker detects access-out-of-bounds for the indices i+1UL, i+2UL and i+3UL.

    Probably i == 15 is checked, although the loopcounter i never has this value in the loop.

    Kind regards

     

    Last edit: Simon Stark 2021-04-28
  • CHR

    CHR - 2021-04-28

    Can you please provide a more complete code snippet? I can't reproduce it so far.

     
  • Simon Stark

    Simon Stark - 2021-04-28

    This snippet is adapted from the code. I will try this with a minimal example and will post this code.

     
  • Simon Stark

    Simon Stark - 2021-04-28

    So I checked with a small code example and cppcheck did not complain. So I started digging and one difference is, that the array size is a #define from a different file in the real code. Could this have some impact?

    #define ARRAY_SIZE (16) //different file
    uint32_t array[ARRAY_SIZE];
    for (uint32_t i = 0; i <= (ARRAY_SIZE-4); i += 4)
      {
            array[i] = someRandomValue;
            array[i+1UL] = 0UL;
            array[i+2UL] = 0UL;
            array[i+3UL] = 0UL;
      }
    

    This works also without a problem. I can suppress or workaround the problem, but I haven't fully understood the issue here.

     
  • Daniel Marjamäki

    So I started digging and one difference is, that the array size is a #define from a different file in the real code. Could this have some impact?

    I doubt it. I think the easiest approach is that you reduce your source file. Remove includes and blocks of code and recheck if cppcheck still complains about this warning..

    I guess the false positive is caused by some little detail in the code that confuse cppcheck.. and it's very hard to guess what that is.

     
  • Dave Ohlsson

    Dave Ohlsson - 2021-04-30

    I have a very similar problem, and I just created this ticket: https://trac.cppcheck.net/ticket/10268#ticket

    Can you reproduce the problem described in that ticket?

     
    • Daniel Marjamäki

      I can reproduce that. Thanks!

       
  • Simon Stark

    Simon Stark - 2021-04-30

    I just took a look at your example and found that I have the same behaviour when the array is processed in a function. If you put the code snippet into the main function, there is no problem. Your observation with the unused parameter is indeed baffling.

     

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.