Menu

False positive: initialized array element reported as uninitialized after guarded loop write

Rodri
2026-08-02
2026-08-03
  • Rodri

    Rodri - 2026-08-02

    Hi, I found a false positive regarding the rule uninitvar.

    In the following C++ program, cppcheck reports that array a is uninitialized when a[0] is returned. However, a[0] is always initialized before the return statement.

    int main() {
      int a[2];
      int i;
      for (i = 0; i < 3; i++) {
        if (i >= 0 && i < 2)
          a[i] = 0;
      }
      return a[0];
    }
    

    The loop executes with i == 0, i == 1, and i == 2. For i == 0 and i == 1, the guard i >= 0 && i < 2 is true, so both a[0] and a[1] are assigned. The final iteration with i == 2 skips the write, but it does not make a[0] uninitialized.

    Actual result

    Cppcheck reports:

    <error id="uninitvar" severity="warning" msg="Uninitialized variable: a" ...>
        <location line="8" column="10"/>
        <location line="5" column="16" info="Assuming condition is false"/>
        <symbol>a</symbol>
    </error>
    

    Cppcheck also reports knownConditionTrueFalse for i >= 0, which is expected and not part of this issue.

    Expected result

    Cppcheck should not report uninitvar for a at return a[0].

    Verification

    The issue was reproduced with:

    cppcheck --output-format=xmlv2 --enable=all guarded_loop_array_init.cpp
    

    Version: 2.21.0

     
  • CHR

    CHR - 2026-08-03

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/14957

     

Log in to post a comment.