brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.8 KiB · d459478 Raw
60 lines · cpp
1// RUN: %check_clang_tidy %s cppcoreguidelines-no-malloc %t \2// RUN: -config='{CheckOptions: \3// RUN:  {cppcoreguidelines-no-malloc.Allocations: "::malloc;::align_malloc;::calloc",\4// RUN:   cppcoreguidelines-no-malloc.Reallocations: "::realloc;::align_realloc",\5// RUN:   cppcoreguidelines-no-malloc.Deallocations: "::free;::align_free"}}' \6// RUN: --7 8using size_t = __SIZE_TYPE__;9 10void *malloc(size_t size);11void *align_malloc(size_t size, unsigned short alignment);12void *calloc(size_t num, size_t size);13void *realloc(void *ptr, size_t size);14void *align_realloc(void *ptr, size_t size, unsigned short alignment);15void free(void *ptr);16void *align_free(void *ptr);17 18void malloced_array() {19  int *array0 = (int *)malloc(sizeof(int) * 20);20  // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: do not manage memory manually; consider a container or a smart pointer [cppcoreguidelines-no-malloc]21 22  int *zeroed = (int *)calloc(20, sizeof(int));23  // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: do not manage memory manually; consider a container or a smart pointer [cppcoreguidelines-no-malloc]24 25  int *aligned = (int *)align_malloc(20 * sizeof(int), 16);26  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: do not manage memory manually; consider a container or a smart pointer [cppcoreguidelines-no-malloc]27 28  // reallocation memory, std::vector shall be used29  char *realloced = (char *)realloc(array0, 50 * sizeof(int));30  // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: do not manage memory manually; consider std::vector or std::string [cppcoreguidelines-no-malloc]31 32  char *align_realloced = (char *)align_realloc(aligned, 50 * sizeof(int), 16);33  // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: do not manage memory manually; consider std::vector or std::string [cppcoreguidelines-no-malloc]34 35  // freeing memory the bad way36  free(realloced);37  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not manage memory manually; use RAII [cppcoreguidelines-no-malloc]38 39  align_free(align_realloced);40  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not manage memory manually; use RAII [cppcoreguidelines-no-malloc]41  42  // check if a call to malloc as function argument is found as well43  free(malloc(20));44  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not manage memory manually; use RAII [cppcoreguidelines-no-malloc]45  // CHECK-MESSAGES: :[[@LINE-2]]:8: warning: do not manage memory manually; consider a container or a smart pointer [cppcoreguidelines-no-malloc]46}47 48/// newing an array is still not good, but not relevant to this checker49void newed_array() {50  int *new_array = new int[10]; // OK(1)51}52 53void arbitrary_call() {54  // we dont want every function to raise the warning even if malloc is in the name55  malloced_array(); // OK(2)56 57  // completely unrelated function call to malloc58  newed_array(); // OK(3)59}60