[clang] [Wunsafe-buffer-usage] Add additional tests to esnure safe accesses to const sized array are not warned (PR #125483)
Malavika Samak via cfe-commits
cfe-commits at lists.llvm.org
Thu Feb 6 23:02:35 PST 2025
https://github.com/malavikasamak updated https://github.com/llvm/llvm-project/pull/125483
>From efd4f3200c4fc2b132157c56e0eaf6c2db844878 Mon Sep 17 00:00:00 2001
From: MalavikaSamak <malavika2 at apple.com>
Date: Fri, 31 Jan 2025 13:40:55 +0530
Subject: [PATCH] [Wunsafe-buffer-usage] Add additional tests to esnure safe
accesses to const sized array are not warned
Add more tests, where the index of the const array access evaluates to a constant and depends on a template
argument.
rdar://143759014
---
.../warn-unsafe-buffer-usage-array.cpp | 35 +++++++++++++++++++
1 file changed, 35 insertions(+)
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp b/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
index e80b54b7c696779..9bfc31bd07b0eee 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
@@ -124,3 +124,38 @@ void array_indexed_const_expr(unsigned idx) {
k = arr[get_const(5)]; // expected-note {{used in buffer access here}}
k = arr[get_const(4)];
}
+
+template<unsigned length>
+consteval bool isNullTerminated(const char (&literal)[length])
+{
+ return literal[length - 1] == '\0';
+}
+
+template <typename T, unsigned M, unsigned N>
+T access2DArray(const T (&arr)[M][N]) {
+ return arr[M-1][N-1];
+}
+
+template<unsigned idx>
+constexpr int access_elements() {
+ int arr[idx + 20];
+ return arr[idx + 1];
+}
+
+// Test array accesses where const sized arrays are accessed safely with indices
+// that evaluate to a const values and depend on template arguments.
+void test_template_methods()
+{
+ constexpr char arr[] = "Good Morning!"; // = {'a', 'b', 'c', 'd', 'e'};
+ isNullTerminated(arr);
+ isNullTerminated("");
+ auto _ = isNullTerminated("hello world\n");
+ access_elements<5>();
+
+ int arr1[3][4] = {
+ {1, 2, 3, 4},
+ {5, 6, 7, 8},
+ {9, 10, 11, 12}
+ };
+ access2DArray(arr1);
+}
More information about the cfe-commits
mailing list