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 *p1 = (int *)malloc(sizeof(int));
28  free(++p1); // no warn
29
30  int *p2 = (int *)malloc(sizeof(int));
31  free(p2);
32  free(p2); // no warn
33
34  int *p3 = (int *)malloc(sizeof(int)); // no warn
35
36  int *p4 = (int *)malloc(sizeof(int));
37  free(p4);
38  int j = *p4; // no warn
39
40  int *p5 = (int *)alloca(sizeof(int));
41  free(p5); // no warn
42}
43
44void testDeleteMalloced() {
45  int *p1 = (int *)malloc(sizeof(int));
46  delete p1;
47  // mismatch-warning@-1{{Memory allocated by malloc() should be deallocated by free(), not 'delete'}}
48
49  int *p2 = (int *)__builtin_alloca(sizeof(int));
50  delete p2; // no warn
51}
52
53void testUseZeroAllocatedMalloced() {
54  int *p1 = (int *)malloc(0);
55  *p1 = 1; // no warn
56}
57
58//----- Test free standard new
59void testFreeOpNew() {
60  void *p = operator new(0);
61  free(p);
62  // mismatch-warning@-1{{Memory allocated by operator new should be deallocated by 'delete', not free()}}
63}
64
65void testFreeNewExpr() {
66  int *p = new int;
67  free(p);
68  // mismatch-warning@-1{{Memory allocated by 'new' should be deallocated by 'delete', not free()}}
69  free(p);
70}
71
72void testObjcFreeNewed() {
73  int *p = new int;
74  NSData *nsdata = [NSData dataWithBytesNoCopy:p length:sizeof(int) freeWhenDone:1];
75  // mismatch-warning@-1{{+dataWithBytesNoCopy:length:freeWhenDone: cannot take ownership of memory allocated by 'new'}}
76}
77
78void testFreeAfterDelete() {
79  int *p = new int;
80  delete p;
81  free(p); // newdelete-warning{{Use of memory after it is freed}}
82}
83
84void testStandardPlacementNewAfterDelete() {
85  int *p = new int;
86  delete p;
87  p = new (p) int; // newdelete-warning{{Use of memory after it is freed}}
88}
89