Home | History | Annotate | Download | only in Analysis
      1 // RUN: %clang_cc1 -analyze -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -verify %s
      2 // RUN: %clang_cc1 -analyze -analyzer-checker=core,cplusplus.NewDelete,alpha.cplusplus.NewDeleteLeaks -std=c++11 -DLEAKS -fblocks -verify %s
      3 #include "Inputs/system-header-simulator-cxx.h"
      4 #include "Inputs/system-header-simulator-objc.h"
      5 
      6 typedef __typeof__(sizeof(int)) size_t;
      7 extern "C" void *malloc(size_t);
      8 extern "C" void free(void *);
      9 
     10 //----------------------------------------------------------------------------
     11 // Check for intersections with unix.Malloc and unix.MallocWithAnnotations 
     12 // checkers bounded with cplusplus.NewDelete.
     13 //----------------------------------------------------------------------------
     14 
     15 //----- malloc()/free() are subjects of unix.Malloc and unix.MallocWithAnnotations
     16 void testMallocFreeNoWarn() {
     17   int i;
     18   free(&i); // no warn
     19 
     20   int *p1 = (int *)malloc(sizeof(int));
     21   free(++p1); // no warn
     22 
     23   int *p2 = (int *)malloc(sizeof(int));
     24   free(p2);
     25   free(p2); // no warn
     26 
     27   int *p3 = (int *)malloc(sizeof(int)); // no warn
     28 
     29   int *p4 = (int *)malloc(sizeof(int));
     30   free(p4);
     31   int j = *p4; // no warn
     32 }
     33 
     34 void testDeleteMalloced() {
     35   int *p = (int *)malloc(sizeof(int));
     36   delete p; // no warn
     37 } 
     38 
     39 //----- Test free standard new
     40 void testFreeOpNew() {
     41   void *p = operator new(0);
     42   free(p);
     43 }
     44 #ifdef LEAKS
     45 // expected-warning@-2 {{Potential leak of memory pointed to by 'p'}}
     46 #endif
     47 
     48 void testFreeNewExpr() {
     49   int *p = new int;
     50   free(p);
     51 }
     52 #ifdef LEAKS
     53 // expected-warning@-2 {{Potential leak of memory pointed to by 'p'}}
     54 #endif
     55 
     56 void testObjcFreeNewed() {
     57   int *p = new int;
     58   NSData *nsdata = [NSData dataWithBytesNoCopy:p length:sizeof(int) freeWhenDone:1];
     59 #ifdef LEAKS
     60   // expected-warning@-2 {{Potential leak of memory pointed to by 'p'}}
     61 #endif
     62 }
     63 
     64 void testFreeAfterDelete() {
     65   int *p = new int;  
     66   delete p;
     67   free(p); // expected-warning{{Use of memory after it is freed}}
     68 }
     69 
     70 void testStandardPlacementNewAfterDelete() {
     71   int *p = new int;  
     72   delete p;
     73   p = new(p) int; // expected-warning{{Use of memory after it is freed}}
     74 }
     75