Skip to content

Commit ac640a2

Browse files
malavikasamakMalavikaSamak
andauthored
[Wunsafe-buffer-usage] Add additional tests to esnure safe accesses to const sized array are not warned (#125483)
Add more tests, where the index of the const array access evaluates to a constant and depends on a template argument. rdar://143759014 Co-authored-by: MalavikaSamak <[email protected]>
1 parent 6b902ef commit ac640a2

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,3 +124,38 @@ void array_indexed_const_expr(unsigned idx) {
124124
k = arr[get_const(5)]; // expected-note {{used in buffer access here}}
125125
k = arr[get_const(4)];
126126
}
127+
128+
template<unsigned length>
129+
consteval bool isNullTerminated(const char (&literal)[length])
130+
{
131+
return literal[length - 1] == '\0';
132+
}
133+
134+
template <typename T, unsigned M, unsigned N>
135+
T access2DArray(const T (&arr)[M][N]) {
136+
return arr[M-1][N-1];
137+
}
138+
139+
template<unsigned idx>
140+
constexpr int access_elements() {
141+
int arr[idx + 20];
142+
return arr[idx + 1];
143+
}
144+
145+
// Test array accesses where const sized arrays are accessed safely with indices
146+
// that evaluate to a const values and depend on template arguments.
147+
void test_template_methods()
148+
{
149+
constexpr char arr[] = "Good Morning!"; // = {'a', 'b', 'c', 'd', 'e'};
150+
isNullTerminated(arr);
151+
isNullTerminated("");
152+
auto _ = isNullTerminated("hello world\n");
153+
access_elements<5>();
154+
155+
int arr1[3][4] = {
156+
{1, 2, 3, 4},
157+
{5, 6, 7, 8},
158+
{9, 10, 11, 12}
159+
};
160+
access2DArray(arr1);
161+
}

0 commit comments

Comments
 (0)