Menu

False positive [constVariable] when a two-dimensional array is written to through an array of pointers

2022-06-22
2022-06-22
  • Siim Ainsaar

    Siim Ainsaar - 2022-06-22

    I analyzed the following file.

    void f(void)
    {
        char a[1][1];
        char *b[1];
        b[0] = a[0];
        **b = 0;
    }
    

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

    $ cppcheck --enable=style --debug t.c 
    Checking t.c ...
    
    
    ##file t.c
    1: void f ( )
    2: {
    3: char a@var1 [@expr3 1 ] [@expr4 1 ] ;
    4: char * b@var2 [@expr5 1 ] ;
    5: b@var2 [@expr6 0 ] =@expr7 a@var1 [@expr8 0 ] ;
    6: *@expr9 *@expr10 b@var2 =@expr11 0 ;
    7: }
    
    
    
    ##Value flow
    Line 3
      1 always 1
      1 always 1
    Line 4
      1 always 1
    Line 5
      b {lifetime[Object]=(b),Uninit*}
      0 always 0
      a {lifetime[Object]=(a),Uninit**}
      0 always 0
    Line 6
      b possible lifetime[Object]=(b)
      = always 0
      0 always 0
    t.c:3:10: style: Variable 'a' can be declared as const array [constVariable]
        char a[1][1];
             ^
    

    As **b points at the first element of a, we're obviously writing there, therefore it would be incorrect to put a into read-only memory. If I try to mark a as const char a[1][1], then cppcheck doesn't warn, but gcc rightfully does.

    Interestingly the false warning disappears if I initialize b on the same line as char *b[1] = {a[0]};

     

    Last edit: Siim Ainsaar 2022-06-22
  • CHR

    CHR - 2022-06-22

    Thanks for reporting, this PR fixes the issue: https://github.com/danmar/cppcheck/pull/4228

     

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.