Skip to content

Commit ea816e8

Browse files
committed
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.
1 parent 9ee9bd1 commit ea816e8

2 files changed

Lines changed: 34 additions & 3 deletions

File tree

‎lib/vf_common.cpp‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -262,9 +262,12 @@ namespace ValueFlow
262262
}
263263
// find the number of elements
264264
size_t count = 1;
265-
for (size_t i = 0; i < var->dimensions().size(); ++i) {
266-
if (var->dimensionKnown(i))
267-
count *= var->dimension(i);
265+
for (const Dimension& dim : var->dimensions()) {
266+
const Value* v = dim.tok ? dim.tok->getKnownValue(Value::ValueType::INT) : nullptr;
267+
if (dim.known)
268+
count *= dim.num;
269+
else if (v && v->intvalue > 0)
270+
count *= v->intvalue;
268271
else
269272
count = 0;
270273
}

‎test/testvalueflow.cpp‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1533,6 +1533,34 @@ class TestValueFlow : public TestFixture {
15331533
ASSERT_EQUALS(1U, values.size());
15341534
ASSERT_EQUALS(2, values.back().intvalue);
15351535

1536+
code = "struct S { char c[4]; };\n"
1537+
"void f() {\n"
1538+
" char a[10 + sizeof(struct S)];\n"
1539+
" x = sizeof(a);\n"
1540+
"}\n";
1541+
values = tokenValues(code, "( a )");
1542+
ASSERT_EQUALS(1U, values.size());
1543+
ASSERT_EQUALS(14, values.back().intvalue);
1544+
1545+
code = "void f() {\n"
1546+
" short s;\n"
1547+
" char a[10 + sizeof(s)];\n"
1548+
" x = sizeof(a);\n"
1549+
"}\n";
1550+
values = tokenValues(code, "( a )");
1551+
ASSERT_EQUALS(1U, values.size());
1552+
ASSERT_EQUALS(12, values.back().intvalue);
1553+
1554+
code = "struct S { char c[4]; };\n"
1555+
"struct S *p;\n"
1556+
"void f() {\n"
1557+
" char a[10 + sizeof(*p)];\n"
1558+
" x = sizeof(a);\n"
1559+
"}\n";
1560+
values = tokenValues(code, "( a )");
1561+
ASSERT_EQUALS(1U, values.size());
1562+
ASSERT_EQUALS(14, values.back().intvalue);
1563+
15361564
#define CHECK(A, B, C, D) \
15371565
do { \
15381566
code = "enum " A " E " B " { E0, E1 };\n" \

0 commit comments

Comments
 (0)