[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
Mon Feb 3 03:36:14 PST 2025


https://github.com/malavikasamak created https://github.com/llvm/llvm-project/pull/125483

Add more tests, where the index of the const array access evaluates to a constant and depends on a template argument.

rdar://143759014

>From 12dc35b91a805c75017d58d400082d2a8959ee31 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        | 33 +++++++++++++++++++
 1 file changed, 33 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..03a7ae5c7a8fb5b 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
@@ -124,3 +124,36 @@ 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]; 
+}
+
+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