From ea816e822c0b937186cae58514d4888df371fa99 Mon Sep 17 00:00:00 2001 From: Jay Beavers Date: Mon, 16 Nov 2026 07:07:02 -0800 Subject: [PATCH] Fix #15225 (FN arrayIndexOutOfBounds: sizeof(arr) unknown when the array dimension contains sizeof of a struct, variable or dereference) valueFlowSetConstantValue() evaluated sizeof(arr) from Variable::dimensions(), but a dimension like 10 + sizeof(struct S) is only marked known by setArrayDimensionsUsingValueFlow(), which runs after all valueflow passes. sizeof(arr) therefore got no value, hiding e.g. arrayIndexOutOfBounds. Fall back to the dimension token's known value, which constant folding has already set by the time the use is reached. --- lib/vf_common.cpp | 9 ++++++--- test/testvalueflow.cpp | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/lib/vf_common.cpp b/lib/vf_common.cpp index 9b1d0387f38..514fdb64edb 100644 --- a/lib/vf_common.cpp +++ b/lib/vf_common.cpp @@ -262,9 +262,12 @@ namespace ValueFlow } // find the number of elements size_t count = 1; - for (size_t i = 0; i < var->dimensions().size(); ++i) { - if (var->dimensionKnown(i)) - count *= var->dimension(i); + for (const Dimension& dim : var->dimensions()) { + const Value* v = dim.tok ? dim.tok->getKnownValue(Value::ValueType::INT) : nullptr; + if (dim.known) + count *= dim.num; + else if (v && v->intvalue > 0) + count *= v->intvalue; else count = 0; } diff --git a/test/testvalueflow.cpp b/test/testvalueflow.cpp index 1e953af1535..0f79bc644a0 100644 --- a/test/testvalueflow.cpp +++ b/test/testvalueflow.cpp @@ -1533,6 +1533,34 @@ class TestValueFlow : public TestFixture { ASSERT_EQUALS(1U, values.size()); ASSERT_EQUALS(2, values.back().intvalue); + code = "struct S { char c[4]; };\n" + "void f() {\n" + " char a[10 + sizeof(struct S)];\n" + " x = sizeof(a);\n" + "}\n"; + values = tokenValues(code, "( a )"); + ASSERT_EQUALS(1U, values.size()); + ASSERT_EQUALS(14, values.back().intvalue); + + code = "void f() {\n" + " short s;\n" + " char a[10 + sizeof(s)];\n" + " x = sizeof(a);\n" + "}\n"; + values = tokenValues(code, "( a )"); + ASSERT_EQUALS(1U, values.size()); + ASSERT_EQUALS(12, values.back().intvalue); + + code = "struct S { char c[4]; };\n" + "struct S *p;\n" + "void f() {\n" + " char a[10 + sizeof(*p)];\n" + " x = sizeof(a);\n" + "}\n"; + values = tokenValues(code, "( a )"); + ASSERT_EQUALS(1U, values.size()); + ASSERT_EQUALS(14, values.back().intvalue); + #define CHECK(A, B, C, D) \ do { \ code = "enum " A " E " B " { E0, E1 };\n" \