[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 12:56:20 PDT 2025


================
@@ -353,6 +367,19 @@ void SizeofExpressionCheck::check(const MatchFinder::MatchResult &Result) {
     diag(E->getBeginLoc(),
          "suspicious usage of 'sizeof(char*)'; do you mean 'strlen'?")
         << E->getSourceRange();
+  } else if (const auto *E = Result.Nodes.getNodeAs<Stmt>("loop-expr")) {
+    auto *SizeofArgTy = Result.Nodes.getNodeAs<Type>("sizeof-arg-type");
+    if (const auto member = dyn_cast<MemberPointerType>(SizeofArgTy)) {
+      SizeofArgTy = member->getPointeeType().getTypePtr();
+    }
+
+    if (const auto type = dyn_cast<ArrayType>(SizeofArgTy)) {
+      CharUnits sSize = Ctx.getTypeSizeInChars(type->getElementType());
+      if (!sSize.isOne()) {
+        diag(E->getBeginLoc(), "suspicious usage of 'sizeof' in the loop")
+            << E->getSourceRange();
----------------
malavikasamak wrote:

The check here is ensuring the size of the array is not equal to the number of elements in the array. If they are equal, using the sizeof operator in the condition of the loop would be acceptable and unlikely to cause an out of bound access.

https://github.com/llvm/llvm-project/pull/143205


More information about the cfe-commits mailing list