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

source code of clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/no-malloc.cpp