1// RUN: %clang_analyze_cc1 -std=c++11 -fblocks %s \
2// RUN:  -verify=newdelete \
3// RUN:  -analyzer-checker=core \
4// RUN:  -analyzer-checker=cplusplus.NewDelete
5
6// RUN: %clang_analyze_cc1 -std=c++11 -DLEAKS -fblocks %s \
7// RUN:   -verify=leak \
8// RUN:   -analyzer-checker=core \
9// RUN:   -analyzer-checker=cplusplus.NewDeleteLeaks
10
11// leak-no-diagnostics
12
13// RUN: %clang_analyze_cc1 -std=c++11 -DLEAKS -fblocks %s \
14// RUN:   -verify=mismatch \
15// RUN:   -analyzer-checker=core \
16// RUN:   -analyzer-checker=unix.MismatchedDeallocator
17
18#include "Inputs/system-header-simulator-cxx.h"
19#include "Inputs/system-header-simulator-objc.h"
20
21typedef __typeof__(sizeof(int)) size_t;
22extern "C" void *malloc(size_t);
23extern "C" void *alloca(size_t);
24extern "C" void free(void *);
25
26void testMallocFreeNoWarn() {
27  int i;
28  free(&i); // no warn
29
30  int *p1 = (int *)malloc(sizeof(int));
31  free(++p1); // no warn
32
33  int *p2 = (int *)malloc(sizeof(int));
34  free(p2);
35  free(p2); // no warn
36
37  int *p3 = (int *)malloc(sizeof(int)); // no warn
38
39  int *p4 = (int *)malloc(sizeof(int));
40  free(p4);
41  int j = *p4; // no warn
42
43  int *p5 = (int *)alloca(sizeof(int));
44  free(p5); // no warn
45}
46
47void testDeleteMalloced() {
48  int *p1 = (int *)malloc(sizeof(int));
49  delete p1;
50  // mismatch-warning@-1{{Memory allocated by malloc() should be deallocated by free(), not 'delete'}}
51
52  int *p2 = (int *)__builtin_alloca(sizeof(int));
53  delete p2; // no warn
54}
55
56void testUseZeroAllocatedMalloced() {
57  int *p1 = (int *)malloc(0);
58  *p1 = 1; // no warn
59}
60
61//----- Test free standard new
62void testFreeOpNew() {
63  void *p = operator new(0);
64  free(p);
65  // mismatch-warning@-1{{Memory allocated by operator new should be deallocated by 'delete', not free()}}
66}
67
68void testFreeNewExpr() {
69  int *p = new int;
70  free(p);
71  // mismatch-warning@-1{{Memory allocated by 'new' should be deallocated by 'delete', not free()}}
72  free(p);
73}
74
75void testObjcFreeNewed() {
76  int *p = new int;
77  NSData *nsdata = [NSData dataWithBytesNoCopy:p length:sizeof(int) freeWhenDone:1];
78  // mismatch-warning@-1{{+dataWithBytesNoCopy:length:freeWhenDone: cannot take ownership of memory allocated by 'new'}}
79}
80
81void testFreeAfterDelete() {
82  int *p = new int;
83  delete p;
84  free(p); // newdelete-warning{{Use of memory after it is freed}}
85}
86
87void testStandardPlacementNewAfterDelete() {
88  int *p = new int;
89  delete p;
90  p = new (p) int; // newdelete-warning{{Use of memory after it is freed}}
91}
92