[clang] [clang-tools-extra] [clang-tidy] Warn about misuse of sizeof operator in loops. (PR #143205)
Malavika Samak via cfe-commits
cfe-commits at lists.llvm.org
Wed Jun 18 11:31:00 PDT 2025
================
@@ -164,6 +164,53 @@ int Test2(MyConstChar* A) {
return sum;
}
+struct A {
+ int array[10];
+};
+
+struct B {
+ struct A a;
+};
+
+void loop_access_elements(int num, struct B b) {
+ struct A arr[10];
+ char buf[20];
+
+ // CHECK-MESSAGES: :[[@LINE+1]]:5: warning: suspicious usage of 'sizeof' in the loop [bugprone-sizeof-expression]
+ for(int i = 0; i < sizeof(arr); i++) {
+ struct A a = arr[i];
+ }
+
+ // Loop warning should not trigger here, even though this code is incorrect
+ // CHECK-MESSAGES: :[[@LINE+2]]:24: warning: suspicious usage of 'sizeof(K)'; did you mean 'K'? [bugprone-sizeof-expression]
+ // CHECK-MESSAGES: :[[@LINE+1]]:34: warning: suspicious usage of 'sizeof(...)/sizeof(...)'; numerator is not a multiple of denominator [bugprone-sizeof-expression]
+ for(int i = 0; i < sizeof(10)/sizeof(A); i++) {
+ struct A a = arr[i];
+ }
+
+ // Should not warn here
+ for(int i = 0; i < sizeof(arr)/sizeof(A); i++) {}
+
+ // CHECK-MESSAGES: :[[@LINE+1]]:5: warning: suspicious usage of 'sizeof' in the loop [bugprone-sizeof-expression]
+ for(int j = 0; j < sizeof(b.a.array); j++) {}
+
+ // Should not warn here
+ for(int i = 0; i < sizeof(buf); i++) {}
+
+ int i = 0;
+ // CHECK-MESSAGES: :[[@LINE+1]]:5: warning: suspicious usage of 'sizeof' in the loop [bugprone-sizeof-expression]
+ while(i <= sizeof(arr)) {i++;}
+
+ i = 0;
+ do {
+ i++;
+ } while(i <= sizeof(arr));
----------------
malavikasamak wrote:
Done.
https://github.com/llvm/llvm-project/pull/143205
More information about the cfe-commits
mailing list