Menu

Array size from one function is wrongly used in an unrelated function

2022-06-16
2022-06-19
  • Siim Ainsaar

    Siim Ainsaar - 2022-06-16

    I analyzed the following file.

    void f(int i, const char* a)
    {
        (void)a[i];
    }
    
    void g(void)
    {
        for (int i = 0; "01234"[i]; ++i)
            f(i, "56789");
    }
    
    void h(void)
    {
        for (int i = 0; "012"[i]; ++i)
            f(i, "345");
    }
    

    cppcheck 2.8 and also the current tip of the main branch give the following false error:

    $ cppcheck --debug minimized.c 
    Checking minimized.c ...
    
    
    ##file minimized.c
    1: void f ( int i@var1 , const char * a@var2 )
    2: {
    3: (@expr5 void ) a@var2 [@expr6 i@var1 ] ;
    4: }
    5:
    6: void g ( )
    7: {
    8: for (@expr7 int i@var3 =@expr8 0 ; "01234" [@expr9 i@var3 ] ; ++@expr10 i@var3 ) {
    9: f (@expr11 i@var3 , "56789" ) ; }
    10: }
    11:
    12: void h ( )
    13: {
    14: for (@expr12 int i@var4 =@expr13 0 ; "012" [@expr14 i@var4 ] ; ++@expr15 i@var4 ) {
    15: f (@expr16 i@var4 , "345" ) ; }
    16: }
    
    
    
    ##Value flow
    Line 3
      a possible {"345"@1,"56789"@2}
      i possible {0@1,2@1,4@2}
    Line 8
      = always 0
      0 always 0
      "01234" always "01234"
    Line 9
      i possible {0,4}
      "56789" always "56789"
    Line 14
      = always 0
      0 always 0
      "012" always "012"
    Line 15
      i possible {0,2}
      "345" always "345"
    minimized.c:3:12: error: Array 'a[4]' accessed at index 4, which is out of bounds. [arrayIndexOutOfBounds]
        (void)a[i];
               ^
    minimized.c:9:11: note: Calling function 'f', 1st argument 'i' value is 4
            f(i, "56789");
              ^
    minimized.c:3:12: note: Array index out of bounds
        (void)a[i];
               ^
    

    If I comment out either g or h, the error disappears. It seems like cppcheck takes the size of the array "a" from h (where it is 4 bytes) and then uses it while analyzing g (where it should be 6 bytes instead).

     
  • Daniel Marjamäki

     

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.