1// RUN: %check_clang_tidy %s bugprone-misplaced-pointer-arithmetic-in-alloc %t
2
3typedef __typeof(sizeof(int)) size_t;
4void *malloc(size_t);
5void *alloca(size_t);
6void *calloc(size_t, size_t);
7void *realloc(void *, size_t);
8
9void bad_malloc(int n) {
10 char *p = (char *)malloc(n) + 10;
11 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: arithmetic operation is applied to the result of malloc() instead of its size-like argument
12 // CHECK-FIXES: char *p = (char *)malloc(n + 10);
13
14 p = (char *)malloc(n) - 10;
15 // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: arithmetic operation is applied to the result of malloc() instead of its size-like argument
16 // CHECK-FIXES: p = (char *)malloc(n - 10);
17
18 p = (char *)malloc(n) + n;
19 // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: arithmetic operation is applied to the result of malloc() instead of its size-like argument
20 // CHECK-FIXES: p = (char *)malloc(n + n);
21
22 p = (char *)malloc(n) - (n + 10);
23 // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: arithmetic operation is applied to the result of malloc() instead of its size-like argument
24 // CHECK-FIXES: p = (char *)malloc(n - (n + 10));
25
26 p = (char *)malloc(n) - n + 10;
27 // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: arithmetic operation is applied to the result of malloc() instead of its size-like argument
28 // CHECK-FIXES: p = (char *)malloc(n - n) + 10;
29 // FIXME: should be p = (char *)malloc(n - n + 10);
30}
31
32void bad_alloca(int n) {
33 char *p = (char *)alloca(n) + 10;
34 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: arithmetic operation is applied to the result of alloca() instead of its size-like argument
35 // CHECK-FIXES: char *p = (char *)alloca(n + 10);
36}
37
38void bad_realloc(char *s, int n) {
39 char *p = (char *)realloc(s, n) + 10;
40 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: arithmetic operation is applied to the result of realloc() instead of its size-like argument
41 // CHECK-FIXES: char *p = (char *)realloc(s, n + 10);
42}
43
44void bad_calloc(int n, int m) {
45 char *p = (char *)calloc(m, n) + 10;
46 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: arithmetic operation is applied to the result of calloc() instead of its size-like argument
47 // CHECK-FIXES: char *p = (char *)calloc(m, n + 10);
48}
49
50void (*(*const alloc_ptr)(size_t)) = malloc;
51
52void bad_indirect_alloc(int n) {
53 char *p = (char *)alloc_ptr(n) + 10;
54 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: arithmetic operation is applied to the result of alloc_ptr() instead of its size-like argument
55 // CHECK-FIXES: char *p = (char *)alloc_ptr(n + 10);
56}
57

source code of clang-tools-extra/test/clang-tidy/checkers/bugprone/misplaced-pointer-arithmetic-in-alloc.c