xref: /llvm-project/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/no-malloc.cpp (revision 89a1d03e2b379e325daa5249411e414bbd995b5e)
1*89a1d03eSRichard // RUN: %check_clang_tidy %s cppcoreguidelines-no-malloc %t
2*89a1d03eSRichard 
3*89a1d03eSRichard using size_t = __SIZE_TYPE__;
4*89a1d03eSRichard 
5*89a1d03eSRichard void *malloc(size_t size);
6*89a1d03eSRichard void *calloc(size_t num, size_t size);
7*89a1d03eSRichard void *realloc(void *ptr, size_t size);
8*89a1d03eSRichard void free(void *ptr);
9*89a1d03eSRichard 
malloced_array()10*89a1d03eSRichard void malloced_array() {
11*89a1d03eSRichard   int *array0 = (int *)malloc(sizeof(int) * 20);
12*89a1d03eSRichard   // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: do not manage memory manually; consider a container or a smart pointer [cppcoreguidelines-no-malloc]
13*89a1d03eSRichard 
14*89a1d03eSRichard   int *zeroed = (int *)calloc(20, sizeof(int));
15*89a1d03eSRichard   // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: do not manage memory manually; consider a container or a smart pointer [cppcoreguidelines-no-malloc]
16*89a1d03eSRichard 
17*89a1d03eSRichard   // reallocation memory, std::vector shall be used
18*89a1d03eSRichard   char *realloced = (char *)realloc(array0, 50 * sizeof(int));
19*89a1d03eSRichard   // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: do not manage memory manually; consider std::vector or std::string [cppcoreguidelines-no-malloc]
20*89a1d03eSRichard 
21*89a1d03eSRichard   // freeing memory the bad way
22*89a1d03eSRichard   free(realloced);
23*89a1d03eSRichard   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not manage memory manually; use RAII [cppcoreguidelines-no-malloc]
24*89a1d03eSRichard 
25*89a1d03eSRichard   // check if a call to malloc as function argument is found as well
26*89a1d03eSRichard   free(malloc(20));
27*89a1d03eSRichard   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not manage memory manually; use RAII [cppcoreguidelines-no-malloc]
28*89a1d03eSRichard   // CHECK-MESSAGES: :[[@LINE-2]]:8: warning: do not manage memory manually; consider a container or a smart pointer [cppcoreguidelines-no-malloc]
29*89a1d03eSRichard }
30*89a1d03eSRichard 
31*89a1d03eSRichard /// newing an array is still not good, but not relevant to this checker
newed_array()32*89a1d03eSRichard void newed_array() {
33*89a1d03eSRichard   int *new_array = new int[10]; // OK(1)
34*89a1d03eSRichard }
35*89a1d03eSRichard 
arbitrary_call()36*89a1d03eSRichard void arbitrary_call() {
37*89a1d03eSRichard   // we dont want every function to raise the warning even if malloc is in the name
38*89a1d03eSRichard   malloced_array(); // OK(2)
39*89a1d03eSRichard 
40*89a1d03eSRichard   // completely unrelated function call to malloc
41*89a1d03eSRichard   newed_array(); // OK(3)
42*89a1d03eSRichard }
43