xref: /llvm-project/clang/docs/analyzer/checkers/newdelete_example.cpp (revision 1a17032b788016299ea4e3c4b53670c6dcd94b4f)
1*1a17032bSKristof Umann void f(int *p);
2*1a17032bSKristof Umann 
testUseMiddleArgAfterDelete(int * p)3*1a17032bSKristof Umann void testUseMiddleArgAfterDelete(int *p) {
4*1a17032bSKristof Umann   delete p;
5*1a17032bSKristof Umann   f(p); // warn: use after free
6*1a17032bSKristof Umann }
7*1a17032bSKristof Umann 
8*1a17032bSKristof Umann class SomeClass {
9*1a17032bSKristof Umann public:
10*1a17032bSKristof Umann   void f();
11*1a17032bSKristof Umann };
12*1a17032bSKristof Umann 
test()13*1a17032bSKristof Umann void test() {
14*1a17032bSKristof Umann   SomeClass *c = new SomeClass;
15*1a17032bSKristof Umann   delete c;
16*1a17032bSKristof Umann   c->f(); // warn: use after free
17*1a17032bSKristof Umann }
18*1a17032bSKristof Umann 
test()19*1a17032bSKristof Umann void test() {
20*1a17032bSKristof Umann   int *p = (int *)__builtin_alloca(sizeof(int));
21*1a17032bSKristof Umann   delete p; // warn: deleting memory allocated by alloca
22*1a17032bSKristof Umann }
23*1a17032bSKristof Umann 
test()24*1a17032bSKristof Umann void test() {
25*1a17032bSKristof Umann   int *p = new int;
26*1a17032bSKristof Umann   delete p;
27*1a17032bSKristof Umann   delete p; // warn: attempt to free released
28*1a17032bSKristof Umann }
29*1a17032bSKristof Umann 
test()30*1a17032bSKristof Umann void test() {
31*1a17032bSKristof Umann   int i;
32*1a17032bSKristof Umann   delete &i; // warn: delete address of local
33*1a17032bSKristof Umann }
34*1a17032bSKristof Umann 
test()35*1a17032bSKristof Umann void test() {
36*1a17032bSKristof Umann   int *p = new int[1];
37*1a17032bSKristof Umann   delete[] (++p);
38*1a17032bSKristof Umann     // warn: argument to 'delete[]' is offset by 4 bytes
39*1a17032bSKristof Umann     // from the start of memory allocated by 'new[]'
40*1a17032bSKristof Umann }
41*1a17032bSKristof Umann 
42