[clang] Add unique_ptr <T[]> accesses to -Wunsafe-buffer-usage (PR #156773)
Jan Korous via cfe-commits
cfe-commits at lists.llvm.org
Wed Sep 17 11:48:09 PDT 2025
================
@@ -31,6 +31,20 @@ void test_unclaimed_use(int *p) { // expected-warning{{'p' is an unsafe pointer
p[5] = 5; // expected-note{{used in buffer access here}}
}
+namespace std {
+inline namespace __1 {
+template <class T> class unique_ptr {
+public:
+ T &operator[](long long i) const;
+};
+} // namespace __1
+} // namespace std
+
+void basic_unique_ptr() {
+ std::unique_ptr<int[]> p1;
+ p1[0]; // expected-warning{{direct access using operator[] on std::unique_ptr<T[]> is unsafe due to lack of bounds checking}}
----------------
jkorous-apple wrote:
Accessing the first element (index 0) is ... special.
We need to keep the C++ Safe Buffers programming model rules consistent for both pointers and arrays to not confuse the users.
Pointer dereference and accessing the first element are identical operations (`buf[0]` being a different syntax for `*buf`).
Our view of built-in pointer dereference is that it is NOT unsafe from the bounds-correctness perspective. While it can lead to invalid memory access it won't be caused by an invalid bound but rather the pointer itself being invalid. For those issues we need a different approach.
Because of that the programming model allows accessing the first element of built-in arrays and pointers and pointer dereference.
Also, the programming model is very intrusive and our goal is to keep it from becoming prohibitively intrusive - in other words we don't want the warning to be overly noisy. By prohibiting pointer dereference and access to the first element we would essentially ban all pointers and arrays (and now `std::unique_ptr<T[]>`).
While I am open to having a discussion about the above I suggest that for now we keep the rules consistent for built-in pointers, arrays and `std::unique_ptr<T[]>` and if we were to prohibit `buff[0]` let's discuss it and possibly make the change also consistently for all three buffer types.
https://github.com/llvm/llvm-project/pull/156773
More information about the cfe-commits
mailing list