1// RUN: %check_clang_tidy %s bugprone-misplaced-operator-in-strlen-in-alloc %t
2
3namespace std {
4typedef __typeof(sizeof(int)) size_t;
5void *malloc(size_t);
6
7size_t strlen(const char *);
8} // namespace std
9
10namespace non_std {
11typedef __typeof(sizeof(int)) size_t;
12void *malloc(size_t);
13
14size_t strlen(const char *);
15} // namespace non_std
16
17void bad_std_malloc_std_strlen(char *name) {
18 char *new_name = (char *)std::malloc(std::strlen(name + 1));
19 // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: addition operator is applied to the argument of strlen
20 // CHECK-FIXES: {{^ char \*new_name = \(char \*\)std::malloc\(}}std::strlen(name) + 1{{\);$}}
21}
22
23void ignore_non_std_malloc_std_strlen(char *name) {
24 char *new_name = (char *)non_std::malloc(std::strlen(name + 1));
25 // CHECK-MESSAGES-NOT: :[[@LINE-1]]:28: warning: addition operator is applied to the argument of strlen
26 // Ignore functions of the malloc family in custom namespaces
27}
28
29void ignore_std_malloc_non_std_strlen(char *name) {
30 char *new_name = (char *)std::malloc(non_std::strlen(name + 1));
31 // CHECK-MESSAGES-NOT: :[[@LINE-1]]:28: warning: addition operator is applied to the argument of strlen
32 // Ignore functions of the strlen family in custom namespaces
33}
34
35void bad_new_strlen(char *name) {
36 char *new_name = new char[std::strlen(name + 1)];
37 // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: addition operator is applied to the argument of strlen
38 // CHECK-FIXES: {{^ char \*new_name = new char\[}}std::strlen(name) + 1{{\];$}}
39}
40
41void good_new_strlen(char *name) {
42 char *new_name = new char[std::strlen(name) + 1];
43 // CHECK-MESSAGES-NOT: :[[@LINE-1]]:20: warning: addition operator is applied to the argument of strlen
44}
45
46class C {
47 char c;
48public:
49 static void *operator new[](std::size_t count) {
50 return ::operator new(count);
51 }
52};
53
54void bad_custom_new_strlen(char *name) {
55 C *new_name = new C[std::strlen(name + 1)];
56 // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: addition operator is applied to the argument of strlen
57 // CHECK-FIXES: {{^ C \*new_name = new C\[}}std::strlen(name) + 1{{\];$}}
58}
59

source code of clang-tools-extra/test/clang-tidy/checkers/bugprone/misplaced-operator-in-strlen-in-alloc.cpp