[clang] [analyzer] Add cplusplus.DestroyedAsWrongType checker (PR #237801)
via cfe-commits
cfe-commits at lists.llvm.org
Wed Nov 4 11:46:42 PST 2026
================
@@ -0,0 +1,358 @@
+// RUN: %clang_analyze_cc1 -std=c++11 %s \
+// RUN: -analyzer-checker=core,cplusplus.DestroyedAsWrongType \
+// RUN: -analyzer-output=text -verify -triple x86_64-unknown-linux-gnu
+
+#include "Inputs/system-header-simulator-cxx.h"
+
+struct A {};
+
+struct B {
+ ~B();
+};
+
+void consume(void *);
+
+void replace_local() {
+ B b;
+ new (&b) A; // expected-note{{Object of type 'A' is created here by placement new}}
+} // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+
+void replace_heap() {
+ B *b = new B;
+ new (b) A; // expected-note{{Object of type 'A' is created here by placement new}}
+ delete b; // expected-warning{{Deleting an object of type 'A' through a pointer to 'B'}} expected-note{{Deleting an object of type 'A' through a pointer to 'B'}}
+}
+
+struct Base {
+ ~Base();
+};
+struct Derived : Base {};
+
+void delete_through_base_without_virtual_dtor() {
+ Base *p = new Base;
+ new (p) Derived; // expected-note{{Object of type 'Derived' is created here by placement new}}
+ delete p; // expected-warning{{Deleting an object of type 'Derived' through a pointer to 'Base'}} expected-note{{Deleting an object of type 'Derived' through a pointer to 'Base'}}
+}
+
+struct Holder { // expected-warning{{Destructor of 'B' is called on storage that holds an object of type 'A'}} expected-note{{Destructor of 'B' is called on storage that holds an object of type 'A'}}
+ B Member;
+};
+
+void replace_member() {
+ Holder h;
+ new (&h.Member) A; // expected-note{{Object of type 'A' is created here by placement new}}
+} // expected-note{{Calling implicit destructor for 'Holder'}}
+
+void destroy_then_replace() {
+ B b;
+ b.~B();
+ new (&b) A; // expected-note{{Object of type 'A' is created here by placement new}}
----------------
mark-zilber wrote:
Moved onto separate lines
https://github.com/llvm/llvm-project/pull/237801
More information about the cfe-commits
mailing list