Skip to content

Commit ef5be43

Browse files
committed
Fixed cppcheck-opensource#7113 (False positive arrayIndexOutOfBounds - using pointer alias with cast)
1 parent 5318970 commit ef5be43

2 files changed

Lines changed: 16 additions & 1 deletion

File tree

lib/checkbufferoverrun.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#include "tokenize.h"
2626
#include "mathlib.h"
2727
#include "symboldatabase.h"
28+
#include "astutils.h"
2829

2930
#include <algorithm>
3031
#include <sstream>
@@ -1083,6 +1084,9 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable()
10831084
continue;
10841085
const Variable *var = it->tokvalue->variable();
10851086
if (var && var->isArray()) {
1087+
if (astCanonicalType(tok) != astCanonicalType(it->tokvalue))
1088+
continue;
1089+
10861090
const ArrayInfo arrayInfo(var, _tokenizer, &_settings->library);
10871091
const MathLib::bigint elements = arrayInfo.numberOfElements();
10881092
if (elements <= 0) // unknown size

test/testbufferoverrun.cpp

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ class TestBufferOverrun : public TestFixture {
141141
TEST_CASE(array_index_string_literal);
142142
TEST_CASE(array_index_same_struct_and_var_name); // #4751 - not handled well when struct name and var name is same
143143
TEST_CASE(array_index_valueflow);
144+
TEST_CASE(array_index_valueflow_pointer);
144145
TEST_CASE(array_index_function_parameter);
145146

146147
TEST_CASE(buffer_overrun_2_struct);
@@ -2059,6 +2060,9 @@ class TestBufferOverrun : public TestFixture {
20592060
"const int X::x[100] = {0}; }", false, "test.cpp");
20602061
ASSERT_EQUALS("", errout.str());
20612062

2063+
}
2064+
2065+
void array_index_valueflow_pointer() {
20622066
check("void f() {\n"
20632067
" int a[10];\n"
20642068
" int *p = a;\n"
@@ -2067,11 +2071,18 @@ class TestBufferOverrun : public TestFixture {
20672071
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Array 'a[10]' accessed at index 20, which is out of bounds.\n", errout.str());
20682072

20692073
check("void f() {\n"
2070-
" int a[X];\n"
2074+
" int a[X];\n" // unknown size
20712075
" int *p = a;\n"
20722076
" p[20] = 0;\n"
20732077
"}");
20742078
ASSERT_EQUALS("", errout.str());
2079+
2080+
check("void f() {\n"
2081+
" int a[2];\n"
2082+
" char *p = (char *)a;\n" // cast
2083+
" p[4] = 0;\n"
2084+
"}");
2085+
ASSERT_EQUALS("", errout.str());
20752086
}
20762087

20772088
void array_index_function_parameter() {

0 commit comments

Comments
 (0)