1 // RUN: %check_clang_tidy %s bugprone-misplaced-operator-in-strlen-in-alloc %t
2 
3 namespace std {
4 typedef __typeof(sizeof(int)) size_t;
5 void *malloc(size_t);
6 
7 size_t strlen(const char *);
8 } // namespace std
9 
10 namespace non_std {
11 typedef __typeof(sizeof(int)) size_t;
12 void *malloc(size_t);
13 
14 size_t strlen(const char *);
15 } // namespace non_std
16 
bad_std_malloc_std_strlen(char * name)17 void 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 
ignore_non_std_malloc_std_strlen(char * name)23 void 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 
ignore_std_malloc_non_std_strlen(char * name)29 void 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 
bad_new_strlen(char * name)35 void 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 
good_new_strlen(char * name)41 void 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 
46 class C {
47   char c;
48 public:
operator new[](std::size_t count)49   static void *operator new[](std::size_t count) {
50     return ::operator new(count);
51   }
52 };
53 
bad_custom_new_strlen(char * name)54 void 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