[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)

Julian Schmidt via cfe-commits cfe-commits at lists.llvm.org
Sun Sep 15 13:44:42 PDT 2024


================
@@ -0,0 +1,34 @@
+// RUN: %check_clang_tidy -std=c++20-or-later %s bugprone-bit-cast-pointers %t
+
+namespace std
+{
+template <typename To, typename From>
+To bit_cast(From from)
+{
+  // Dummy implementation for the purpose of the test.
+  // We don't want to include <cstring> to get std::memcpy.
+  To to{};
+  return to;
+}
+}
+
+void pointer2pointer()
+{
+  int x{};
+  float bad = *std::bit_cast<float*>(&x); // UB, but looks safe due to std::bit_cast
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: do not use std::bit_cast on pointers; use it on values instead [bugprone-bit-cast-pointers]
+  float good = std::bit_cast<float>(x);   // Well-defined
+}
----------------
5chmidti wrote:

Could you add
```c++
  using IntPtr = int*;
  using FloatPtr = float*;
  IntPtr i;
  float bad2 = *std::bit_cast<FloatPtr>(i);
```
to the test as well? It passes, but aliased types should be tested as well.

https://github.com/llvm/llvm-project/pull/108083


More information about the cfe-commits mailing list