57 lines · c
1// RUN: %check_clang_tidy %s bugprone-misplaced-pointer-arithmetic-in-alloc %t2 3typedef __typeof(sizeof(int)) size_t;4void *malloc(size_t);5void *alloca(size_t);6void *calloc(size_t, size_t);7void *realloc(void *, size_t);8 9void bad_malloc(int n) {10 char *p = (char *)malloc(n) + 10;11 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: arithmetic operation is applied to the result of malloc() instead of its size-like argument12 // CHECK-FIXES: char *p = (char *)malloc(n + 10);13 14 p = (char *)malloc(n) - 10;15 // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: arithmetic operation is applied to the result of malloc() instead of its size-like argument16 // CHECK-FIXES: p = (char *)malloc(n - 10);17 18 p = (char *)malloc(n) + n;19 // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: arithmetic operation is applied to the result of malloc() instead of its size-like argument20 // CHECK-FIXES: p = (char *)malloc(n + n);21 22 p = (char *)malloc(n) - (n + 10);23 // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: arithmetic operation is applied to the result of malloc() instead of its size-like argument24 // CHECK-FIXES: p = (char *)malloc(n - (n + 10));25 26 p = (char *)malloc(n) - n + 10;27 // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: arithmetic operation is applied to the result of malloc() instead of its size-like argument28 // CHECK-FIXES: p = (char *)malloc(n - n) + 10;29 // FIXME: should be p = (char *)malloc(n - n + 10);30}31 32void bad_alloca(int n) {33 char *p = (char *)alloca(n) + 10;34 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: arithmetic operation is applied to the result of alloca() instead of its size-like argument35 // CHECK-FIXES: char *p = (char *)alloca(n + 10);36}37 38void bad_realloc(char *s, int n) {39 char *p = (char *)realloc(s, n) + 10;40 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: arithmetic operation is applied to the result of realloc() instead of its size-like argument41 // CHECK-FIXES: char *p = (char *)realloc(s, n + 10);42}43 44void bad_calloc(int n, int m) {45 char *p = (char *)calloc(m, n) + 10;46 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: arithmetic operation is applied to the result of calloc() instead of its size-like argument47 // CHECK-FIXES: char *p = (char *)calloc(m, n + 10);48}49 50void (*(*const alloc_ptr)(size_t)) = malloc;51 52void bad_indirect_alloc(int n) {53 char *p = (char *)alloc_ptr(n) + 10;54 // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: arithmetic operation is applied to the result of alloc_ptr() instead of its size-like argument55 // CHECK-FIXES: char *p = (char *)alloc_ptr(n + 10);56}57