1// C, C++
2void test() {
3 int *p = (int *)malloc(sizeof(int));
4 delete p; // warn
5}
6
7// C, C++
8void __attribute((ownership_returns(malloc))) *user_malloc(size_t);
9void __attribute((ownership_takes(malloc, 1))) *user_free(void *);
10
11void __attribute((ownership_returns(malloc1))) *user_malloc1(size_t);
12void __attribute((ownership_takes(malloc1, 1))) *user_free1(void *);
13
14void test() {
15 int *p = (int *)user_malloc(sizeof(int));
16 delete p; // warn
17}
18
19// C, C++
20void test() {
21 int *p = new int;
22 free(p); // warn
23}
24
25// C, C++
26void test() {
27 int *p = new int[1];
28 realloc(p, sizeof(long)); // warn
29}
30
31// C, C++
32void test() {
33 int *p = user_malloc(10);
34 user_free1(p); // warn
35}
36
37// C, C++
38template <typename T>
39struct SimpleSmartPointer {
40 T *ptr;
41
42 explicit SimpleSmartPointer(T *p = 0) : ptr(p) {}
43 ~SimpleSmartPointer() {
44 delete ptr; // warn
45 }
46};
47
48void test() {
49 SimpleSmartPointer<int> a((int *)malloc(4));
50}
51
52// C++
53void test() {
54 int *p = (int *)operator new(0);
55 delete[] p; // warn
56}
57
58// Objective-C, C++
59void test(NSUInteger dataLength) {
60 int *p = new int;
61 NSData *d = [NSData dataWithBytesNoCopy:p
62 length:sizeof(int) freeWhenDone:1];
63 // warn +dataWithBytesNoCopy:length:freeWhenDone: cannot take
64 // ownership of memory allocated by 'new'
65}
66
67

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of clang/docs/analyzer/checkers/mismatched_deallocator_example.cpp