Debian Codegraph @

clang/docs/analyzer/checkers/mismatched_deallocator_example.cpp

raw
1 // C, C++
2 void test() {
3 int *p = (int *)malloc(sizeof(int));
4 delete p; // warn
5 }
6
7 // C, C++
8 void __attribute((ownership_returns(malloc))) *user_malloc(size_t);
9 void __attribute((ownership_takes(malloc, 1))) *user_free(void *);
10
11 void __attribute((ownership_returns(malloc1))) *user_malloc1(size_t);
12 void __attribute((ownership_takes(malloc1, 1))) *user_free1(void *);
13
14 void test() {
15 int *p = (int *)user_malloc(sizeof(int));
16 delete p; // warn
17 }
18
19 // C, C++
20 void test() {
21 int *p = new int;
22 free(p); // warn
23 }
24
25 // C, C++
26 void test() {
27 int *p = new int[1];
28 realloc(p, sizeof(long)); // warn
29 }
30
31 // C, C++
32 void test() {
33 int *p = user_malloc(10);
34 user_free1(p); // warn
35 }
36
37 // C, C++
38 template <typename T>
39 struct SimpleSmartPointer {
40 T *ptr;
41
42 explicit SimpleSmartPointer(T *p = 0) : ptr(p) {}
43 ~SimpleSmartPointer() {
44 delete ptr; // warn
45 }
46 };
47
48 void test() {
49 SimpleSmartPointer<int> a((int *)malloc(4));
50 }
51
52 // C++
53 void test() {
54 int *p = (int *)operator new(0);
55 delete[] p; // warn
56 }
57
58 // Objective-C, C++
59 void 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