Skip to content

Fix #14992, #14989 FP arrayIndexOutOfBounds and negativeIndex in unreachable branch - #9046

Open
APX403 wants to merge 1 commit into
cppcheck-opensource:mainfrom
APX403:fix-14992-14989
Open

APX403 wants to merge 1 commit into
cppcheck-opensource:mainfrom
APX403:fix-14992-14989

Conversation

@APX403

@APX403 APX403 commented Nov 19, 2026

Copy link
Copy Markdown

arrayIndex() reports indexes in branches that can never be taken: a discarded if constexpr branch (#14992), and a branch whose condition is known once the template is instantiated (#14989). Both are errors, so they show up in a default run:

constexpr char arr[] = {'A', 'B', 'C', 'D'};

int get(int idx) {
    if constexpr (4 < sizeof(arr)/sizeof(arr[0])) {
        return arr[4];
    } else {
        return -1;
    }
}
t14992.cpp:5:19: error: Array 'arr[4]' accessed at index 4, which is out of bounds. [arrayIndexOutOfBounds]
struct S {
  int a[10];
};

template <int N>
int g(const S& x)
{
  if (N == 7)
    return x.a[N];
  else
    return x.a[N - 17];
}

int f(const S& x)
{
  return g<7>(x);
}
t14989b.cpp:11:15: error: Array 'x.a[10]' accessed at index -10, which is out of bounds. [negativeIndex]

The token loop of arrayIndex() (checkbufferoverrun.cpp#L301-L306) now starts with skipUnreachableBranch(), like the loops in checktype.cpp, checkother.cpp, checkfunctions.cpp and checkexceptionsafety.cpp. The full example of #14989 no longer gives its six errors. An out-of-bounds index in an if constexpr branch that is taken is still reported, which the test checks too. As with the other checks, an index in a block such as if (false) is no longer reported either.

I don't have a Trac account, so I can't assign the tickets to myself.

…achable branch

arrayIndex() checked the indexes of every branch, also of a discarded
if constexpr branch and of a branch whose condition is known once the
template is instantiated. Skip the unreachable branches with
skipUnreachableBranch(), as the other checks that walk all tokens do.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant